Пример #1
1
  public static String doPost(
      String url, Map<String, String> headers, Map<String, String> params, boolean isHttps) {

    HttpClient client = isHttps ? createSSLClientDefault() : HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    if (headers == null) {
      post.setHeader("Content-Type", "text/html;charset=utf-8");
    } else {
      for (String key : headers.keySet()) {
        post.setHeader(key, headers.get(key));
      }
    }
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    Set<String> keySet = params.keySet();
    for (String key : keySet) {
      nvps.add(new BasicNameValuePair(key, params.get(key)));
    }
    try {
      // UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, "UTF-8");
      HttpEntity entity = EntityBuilder.create().setParameters(nvps).build();
      System.out.println(nvps.get(1).getValue());
      System.out.println(StringUtils.streamToStringReader(entity.getContent()));
      post.setEntity(entity);
      HttpResponse response = client.execute(post);
      return httpClientResponse(response);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }
Пример #2
1
 public static String postStream(String url, String data) {
   InputStream is = null;
   try {
     DefaultHttpClient httpClient = new DefaultHttpClient();
     HttpPost httpPost = new HttpPost(url);
     httpPost.setEntity(new StringEntity(data));
     httpPost.setHeader("Accept", "application/json");
     httpPost.setHeader("Content-type", "application/json");
     HttpResponse httpResponse = httpClient.execute(httpPost);
     Log.i("Httpresponse:", httpResponse.toString());
     HttpEntity httpEntity = httpResponse.getEntity();
     is = httpEntity.getContent();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (ClientProtocolException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (IOException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   }
   Log.e("is:", is.toString());
   return readStream(is);
 }
Пример #3
1
 public static String postStream2(String url, String data) {
   InputStream is = null;
   String flag = "";
   try {
     DefaultHttpClient httpClient = new DefaultHttpClient();
     HttpPost httpPost = new HttpPost(url);
     httpPost.setEntity(new StringEntity(data));
     httpPost.setHeader("Accept", "application/json");
     httpPost.setHeader("Content-type", "application/json");
     HttpResponse httpResponse = httpClient.execute(httpPost);
     Log.i("Httpresponse:", httpResponse.toString());
     Log.i("Http Response:", String.valueOf(httpResponse.getStatusLine().getStatusCode()));
     if (String.valueOf(httpResponse.getStatusLine().getStatusCode()).trim().equals("404")) {
       flag = "false";
     } else {
       flag = "true";
     }
     HttpEntity httpEntity = httpResponse.getEntity();
     is = httpEntity.getContent();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (ClientProtocolException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (IOException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   }
   Log.e("is:", is.toString());
   return flag;
 }
Пример #4
0
  public String POST(String url, JSONObject json) {
    InputStream inputStream = null;
    String result = "";
    try {
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);
      // Convert the given json object to its stirng form
      final String jsonString = json.toString();
      final StringEntity se = new StringEntity(jsonString);
      // Set the contents of the post
      httpPost.setEntity(se);
      httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");
      httpPost.setHeader("CsrfToken", "nocheck");
      // Execute the POST
      HttpResponse httpResponse = httpclient.execute(httpPost, httpContext);
      // Get the response
      inputStream = httpResponse.getEntity().getContent();
      if (inputStream != null) result = convertInputStreamToString(inputStream);
      else result = "Did not work!";

    } catch (Exception e) {
      Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
  }
Пример #5
0
  /*
   * The following method simply takes a URL, sends a POST request to the
   * server and returns an input stream, which can be read and parsed.
   */
  public static InputStream postData(String url, String jsonData) {

    DefaultHttpClient client =
        new DefaultHttpClient(KaribuApplication.clientConnectionManager, KaribuApplication.params);

    HttpPost postRequest = new HttpPost(url);

    try {
      postRequest.setEntity(new StringEntity(jsonData));
      postRequest.setHeader("Accept", "application/json");
      postRequest.setHeader("Content-type", "application/json");

      HttpResponse postResponse = client.execute(postRequest);
      final int statusCode = postResponse.getStatusLine().getStatusCode();

      if (statusCode != HttpStatus.SC_OK) {
        Log.w("KaribuApplication", "Error " + statusCode + " for URL " + url);
        return null;
      }

      return postResponse.getEntity().getContent();

    } catch (IOException e) {
      postRequest.abort();
      Log.w("KaribuApplication", "Error for URL " + url, e);
    }

    return null;
  }
  /** {@inheritDoc} */
  private boolean sendPlfInformation(String accessTokencode) {
    try {
      String url = softwareRegistrationHost + "/portal/rest/registerSoftware/register";
      HttpClient client = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);

      JsonPlatformInfo jsonPlatformInfo = platformInformationRESTService.getJsonPlatformInfo();
      JSONObject jsonObj = new JSONObject(jsonPlatformInfo);

      String input = jsonObj.toString();

      httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");
      httpPost.setHeader("Authorization", "Bearer " + accessTokencode);
      httpPost.setEntity(new StringEntity(input));

      HttpResponse response = client.execute(httpPost);

      if (response.getStatusLine().getStatusCode() != 200) {
        LOG.warn("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        return false;
      }
      return true;
    } catch (Exception e) {
      LOG.warn("Can not send Platform information to eXo community", e);
      return false;
    }
  }
Пример #7
0
 public void delete(String feedUrl, Operation operation) throws IOException {
   HttpPost post = new HttpPost(feedUrl);
   String etag = operation.inOutEtag;
   post.setHeader(X_HTTP_METHOD_OVERRIDE, "DELETE");
   post.setHeader(IF_MATCH, etag != null ? etag : "*");
   callMethod(post, operation);
 }
    private byte[] postRequest(String url, byte[] drmRequest) {
      HttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url + "&signedRequest=" + new String(drmRequest));

      Log.d(TAG, "PostRequest:" + httpPost.getRequestLine());
      try {
        // Add data
        httpPost.setHeader("Accept", "*/*");
        httpPost.setHeader("User-Agent", "Widevine CDM v1.0");
        httpPost.setHeader("Content-Type", "application/json");

        // Execute HTTP Post Request
        HttpResponse response = httpClient.execute(httpPost);

        byte[] responseBody;
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode == 200) {
          responseBody = EntityUtils.toByteArray(response.getEntity());
        } else {
          Log.d(TAG, "Server returned HTTP error code " + responseCode);
          return null;
        }
        return responseBody;
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return null;
    }
Пример #9
0
  @Override
  protected Void doInBackground(Void... params) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPostRequest = new HttpPost(url);

    try {
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
      nameValuePairs.add(new BasicNameValuePair("data", request));

      httpPostRequest.setHeader("Content-type", "application/x-www-form-urlencoded");
      httpPostRequest.setHeader("Accept", "application/json");
      httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      HttpResponse response = httpClient.execute(httpPostRequest);
      StatusLine status = response.getStatusLine();
      Log.v("Status response", status.getStatusCode() + "");

      HttpEntity entity = response.getEntity();

      if (entity != null) {
        InputStream inputStream = entity.getContent();
        responseResult = convertStreamToString(inputStream);
        inputStream.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      responseResult = "";
    }

    return null;
  }
Пример #10
0
  public String simplePost(JSONObject jsonParam, String remoteUrl, String charSet) {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    String key = "";
    for (Iterator<?> iterator = jsonParam.keys(); iterator.hasNext(); ) {
      key = String.valueOf(iterator.next());
      params.add(new BasicNameValuePair(key, jsonParam.getString(key)));
    }

    UrlEncodedFormEntity entity = null;
    try {
      entity = new UrlEncodedFormEntity(params, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    HttpPost post = new HttpPost(remoteUrl);
    post.setHeader("accept", "*/*");
    post.setHeader("connection", "Keep-Alive");
    post.setEntity(entity);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = null;
    HttpEntity httpEntity = null;
    String result = "";
    try {
      response = client.execute(post);
      httpEntity = response.getEntity();
      result = EntityUtils.toString(httpEntity);
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }
Пример #11
0
  public HttpResult post(String url, String request, SyncProcessor processor) throws ComException {
    HttpClient httpclient = createHttpClient();
    HttpPost httppost = new HttpPost(url);

    try {

      String jsonData = request;
      httppost.setHeader("Content-type", "application/json");
      httppost.setHeader("charset", "utf-8");
      StringEntity se = new StringEntity(jsonData, "UTF-8");

      se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
      //    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "utf-8"));

      httppost.setEntity(se);

      HttpResponse response = httpclient.execute(httppost);

      String responseString = EntityUtils.toString(response.getEntity());

      HttpResult rv =
          new HttpResult(response, responseString, response.getStatusLine().getStatusCode());
      return rv;

    } catch (Exception ex) {

      throw new ComException("WsComService.AskServer", ex);
    }
  }
Пример #12
0
  // getting authorisation token
  private AuthToken getAuthToken() {
    AuthToken token = null;
    try {
      String urlApiKey = URLEncoder.encode(Util.TwitterKey, "UTF-8");
      String urlApiSecret = URLEncoder.encode(Util.TwitterSecret, "UTF-8");
      String combined = urlApiKey + ":" + urlApiSecret;
      String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

      HttpPost httpPost = new HttpPost(TwitterTokenURL);
      httpPost.setHeader("Authorization", "Basic " + base64Encoded);
      httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
      httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
      String rawAuthorization = getResponseBody(httpPost);

      // decoding authentication token
      JSONObject jObj = new JSONObject(rawAuthorization);
      token = new AuthToken();
      token.setTokenType(jObj.getString("token_type"));
      token.setAccessToken(jObj.getString("access_token"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return token;
  }
Пример #13
0
  /*
   * @throws IOException If an input or output exception occurred
   *
   * @param The Hub address you want to publish it to
   *
   * @param The topic_url you want to publish
   *
   * @return HTTP Response code. 200 is ok. Anything else smells like trouble
   */
  public int execute(String hub, String topic_url, String message, String signature)
      throws Exception {

    if ((hub != null) && (topic_url != null) && (message != null) && (signature != null)) {

      // URL should validate if the strings are really URLs. Will throw
      // Exception if it isn't
      @SuppressWarnings("unused")
      URL verifying_topic_url = new URL(topic_url);
      @SuppressWarnings("unused")
      URL hub_url = new URL(hub);

      HttpPost httppost = new HttpPost(hub);

      List<NameValuePair> nvps = new ArrayList<NameValuePair>();
      nvps.add(new BasicNameValuePair("hub.mode", "publish"));
      nvps.add(new BasicNameValuePair("hub.url", topic_url));
      nvps.add(new BasicNameValuePair("hub.content", message));
      nvps.add(new BasicNameValuePair("hub.signature", signature));

      httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

      httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
      httppost.setHeader("User-agent", "pubsubhubbub 0.3");

      GetThread thread = new GetThread(httpClient, httppost);
      thread.start();
      thread.join();

      return thread.httpresponse.getStatusLine().getStatusCode();
    }
    return 400;
  }
Пример #14
0
  public static String postJSON(final String url, JSONObject params, final String headValue)
      throws Exception {
    HttpPost httpRequest = new HttpPost(url);
    if (headValue != null) {
      httpRequest.setHeader(CUSTOM_HEAD_NAME, headValue);
    }
    httpRequest.setHeader("Content-Type", CONTENT_TYPE);
    httpRequest.setEntity(new StringEntity(params.toString(), HTTP.UTF_8));
    HttpResponse httpResponse;

    try {
      httpResponse = HttpManager.execute(httpRequest);
    } catch (SocketException e) {
      httpResponse = HttpManager.execute(httpRequest);
    }
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    if (statusCode == 200) {
      return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
    } else if (statusCode == 302) {
      throw new IOException("302");
    } else {
      String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
      throw new ApiRequestErrorException(result);
    }
  }
Пример #15
0
  private boolean loginWithAccessCode(
      DefaultHttpClient httpClient, HttpContext context, String bankAccount, String accessCode)
      throws IOException, RetrieverException {
    String logonToken =
        requestLogonToken(
            httpClient,
            context,
            "https://bankservices.rabobank.nl/services/balanceviewsettings/v1");

    HttpPost post = new HttpPost("https://bankservices.rabobank.nl/auth/logonac/v2/");
    final String requestXml = String.format(AC_LOGIN, accessCode, bankAccount, logonToken);
    StringEntity stringEntity = new StringEntity(requestXml, "application/xml", "UTF-8");
    post.setEntity(stringEntity);
    post.setHeader("Content-Type", "application/xml");
    post.setHeader("Accept", "application/xml");

    HttpResponse response = httpClient.execute(post, context);
    if (response.getStatusLine().getStatusCode() != 200) {
      post.abort();
      throw new RetrieverException(
          "Expected HTTP 200 from " + post.getURI() + ", received " + response.getStatusLine());
    }

    post.abort();
    return true;
  }
Пример #16
0
  public static byte[] httpPost(String url, String entity) {
    if (url == null || url.length() == 0) {
      Log.e(TAG, "httpPost, url is null");
      return null;
    }

    HttpClient httpClient = getNewHttpClient();

    HttpPost httpPost = new HttpPost(url);

    try {
      httpPost.setEntity(new StringEntity(entity));
      httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");

      HttpResponse resp = httpClient.execute(httpPost);
      if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode());
        return null;
      }

      return EntityUtils.toByteArray(resp.getEntity());
    } catch (Exception e) {
      Log.e(TAG, "httpPost exception, e = " + e.getMessage());
      e.printStackTrace();
      return null;
    }
  }
Пример #17
0
    private void sendMessage(final String suffix, final HttpEntity message) throws SenderException {
      HttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
      HttpConnectionParams.setSoTimeout(httpParams, 5000);
      HttpClient httpClient = new DefaultHttpClient(httpParams);

      HttpPost httppost = new HttpPost(url + "/" + suffix + "/" + buildId);
      if (message != null) {
        httppost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-protobuf");
        httppost.setEntity(message);
      }
      if (!secret.isEmpty()) {
        httppost.setHeader(DASH_SECRET_HEADER, secret);
      }
      StatusLine status;
      try {
        status = httpClient.execute(httppost).getStatusLine();
      } catch (IOException e) {
        throw new SenderException("Error sending results to " + url, e);
      }
      if (status.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
        throw new SenderException(
            "Permission denied while sending results to "
                + url
                + ". Did you specified --dash_secret?");
      }
    }
  @Override
  public String sendPostPara(String url, List<NameValuePair> urlPara) throws Exception {

    // System.out.println("------------------HttpSEND-Para------------");

    HttpPost post = new HttpPost(url);
    post.setHeader("User-Agent", USER_AGENT);
    post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    post.setHeader("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");
    // post.setHeader("Connection", "keep-alive");
    // post.setHeader("Content-Type", "text/html; charset=UTF-8");

    HttpEntity entity = new UrlEncodedFormEntity(urlPara, "UTF-8");

    // post.setEntity(new UrlEncodedFormEntity(urlPara));;
    post.setEntity(entity);

    HttpResponse response = httpClient.execute(post);
    BufferedReader bufferedReader =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuilder stringBuilder = new StringBuilder();
    String inputLine = "";

    while ((inputLine = bufferedReader.readLine()) != null) {
      stringBuilder.append(inputLine);
    }

    bufferedReader.close();
    // System.out.println("------------------HttpSEND-END-------");
    return stringBuilder.toString();
  }
  public void send(String payload, TransportReceiver receiver) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost();
    post.setHeader("Content-Type", "application/json;charset=UTF-8");
    post.setHeader("Cookie", cookie);

    post.setURI(uri);
    Throwable ex;
    try {
      post.setEntity(new StringEntity(payload, "UTF-8"));
      HttpResponse response = client.execute(post);
      if (200 == response.getStatusLine().getStatusCode()) {
        String contents = readStreamAsString(response.getEntity().getContent());
        receiver.onTransportSuccess(contents);
      } else {
        receiver.onTransportFailure(new ServerFailure(response.getStatusLine().getReasonPhrase()));
      }
      return;
    } catch (UnsupportedEncodingException e) {
      ex = e;
    } catch (ClientProtocolException e) {
      ex = e;
    } catch (IOException e) {
      ex = e;
    }
    receiver.onTransportFailure(new ServerFailure(ex.getMessage()));
  }
Пример #20
0
  public static final String executePost(String url) {
    try {
      HttpPost httppost = new HttpPost(url);

      httppost.setHeader("User-Agent", USER_AGENT);
      httppost.setHeader("Accept-Charset", "utf-8");
      httppost.setHeader("Cache-Control", "max-age=3, must-revalidate, private");
      httppost.setHeader(
          "Authorization",
          "OAuth oauth_token=2d62f7b3de642cdd402f62e42fba0b25, oauth_consumer_key=a324957217164fd1d76b4b60d037abec, oauth_version=1.0, oauth_signature_method=HMAC-SHA1, oauth_timestamp=1322049404, oauth_nonce=-5195915877644743836, oauth_signature=wggOr1ia7juVbG%2FZ2ydImmiC%2Ft4%3D");

      HttpClient client = theThreadSafeHttpClient();
      HttpResponse response = client.execute(httppost);
      HttpEntity entity = response.getEntity();
      if (entity != null) {
        client.getConnectionManager().closeExpiredConnections();
        return EntityUtils.toString(entity, HTTP.UTF_8);
      }

    } catch (HttpResponseException e) {
      System.err.println(e.getMessage());

    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }
Пример #21
0
  public static String executeMultipartPost(
      String postUrl, Map<String, Object> params, String accessTokens) throws Exception {
    try {
      HttpClient httpClient = theThreadSafeHttpClient();
      HttpPost postRequest = new HttpPost(postUrl);
      postRequest.addHeader("Accept-Charset", HTTP.UTF_8);
      postRequest.addHeader("User-Agent", MOBILE_USER_AGENT);
      postRequest.setHeader("Cache-Control", "max-age=3, must-revalidate, private");
      postRequest.setHeader(
          "Authorization",
          "OAuth oauth_token="
              + accessTokens
              + ", oauth_consumer_key=a324957217164fd1d76b4b60d037abec, oauth_version=1.0, oauth_signature_method=HMAC-SHA1, oauth_timestamp=1322049404, oauth_nonce=-5195915877644743836, oauth_signature=wggOr1ia7juVbG%2FZ2ydImmiC%2Ft4%3D");

      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
      Set<String> names = params.keySet();
      for (String name : names) {
        Object value = params.get(name);
        if (value instanceof StringBody) {
          reqEntity.addPart(name, (StringBody) value);
        } else if (value instanceof File) {
          reqEntity.addPart("media", new FileBody((File) value));
        }
      }
      postRequest.setEntity(reqEntity);

      HttpResponse response = httpClient.execute(postRequest);
      return EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
    } catch (Exception e) {
      // handle exception here
      e.printStackTrace();
    }
    return "";
  }
Пример #22
0
  public void doCheckin() throws IOException {
    HttpPost request = new HttpPost("https://android.clients.google.com/checkin");
    request.setHeader("Content-type", "application/x-protobuffer");
    request.setHeader("Content-Encoding", "gzip");
    request.setHeader("Accept-Encoding", "gzip");
    request.setHeader("User-Agent", "Android-Checkin/2.0 (maguro JRO03L); gzip");

    request.setEntity(new ByteArrayEntity(generateCheckinPayload()));

    try {
      HttpResponse response = this.httpclient.execute(request);
      HttpEntity entity = response.getEntity();
      if (entity == null) throw new IOException(response.getStatusLine().toString());

      byte[] response_bytes = Helpers.inputStreamToBytes(entity.getContent());
      AndroidCheckinResponse parsed_response = AndroidCheckinResponse.parseFrom(response_bytes);

      long aid = parsed_response.getAndroidId();
      if (aid == 0)
        throw new IOException(
            "Can't find android_id" + " // " + response.getStatusLine().toString());

      this.androidId = Long.toString(aid, 16);
    } finally {
      request.releaseConnection();
    }
  }
    @Override
    protected String doInBackground(String... params) {
      String result = "";

      try {
        String url = "http://listasupermercadows.apphb.com/api/listaws/";

        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(url);

        String json = "";

        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("Nome", produto.getNome());
        jsonObject.accumulate("Quantidade", produto.getQuantidade());
        jsonObject.accumulate("ContaId", produto.getContaId());

        json = jsonObject.toString();

        StringEntity se = new StringEntity(json, "UTF-8");

        httpPost.setEntity(se);

        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse httpResponse = httpclient.execute(httpPost);

      } catch (Exception e) {
        Log.d("Erro", e.getLocalizedMessage());
      }
      return result;
    }
Пример #24
0
  // Register new user
  public static String POST(String url, User user) {
    InputStream inputStream = null;
    String result = "";
    int code = 0;
    try {

      // 1. create HttpClient
      HttpClient httpclient = new DefaultHttpClient();

      // 2. make POST request to the given URL
      HttpPost httpPost = new HttpPost(url);

      String json = "";

      // 3. build jsonObject
      JSONObject jsonObject = new JSONObject();
      jsonObject.accumulate("name", user.getName());
      jsonObject.accumulate("mail", user.getEmail());
      jsonObject.accumulate("password", user.getPassword());

      // 4. convert JSONObject to JSON to String
      json = jsonObject.toString();

      // ** Alternative way to convert Person object to JSON string usin Jackson Lib
      // ObjectMapper mapper = new ObjectMapper();
      // json = mapper.writeValueAsString(person);

      // 5. set json to StringEntity
      StringEntity se = new StringEntity(json);

      // 6. set httpPost Entity
      httpPost.setEntity(se);

      // 7. Set some headers to inform server about the type of the content
      httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");

      // 8. Execute POST request to the given URL
      HttpResponse httpResponse = httpclient.execute(httpPost);
      code = httpResponse.getStatusLine().getStatusCode();
      if (code == 500) {
        throw new Exception();
      }
      System.out.println("Status------------------> " + code);
      // 9. receive response as inputStream
      inputStream = httpResponse.getEntity().getContent();

      // 10. convert inputstream to string
      if (inputStream != null) result = convertInputStreamToString(inputStream);
      else result = "Did not work!";

    } catch (Exception e) {
      // Log.d("InputStream", e.getLocalizedMessage());
      return String.valueOf(code);
    }

    // 11. return result
    return String.valueOf(code);
  }
  public String POST(String url) {
    String tmp;
    if (result == null) {
      tmp = textViewDesc.getText().toString();
    } else {
      tmp = result;
    }
    ArrayList<String> items = new ArrayList<>();
    items.addAll(Arrays.asList(textViewTags.getText().toString().split("\\s*,\\s*")));
    NormalQuestion normalQuestion =
        new NormalQuestion(textViewTitle.getText().toString(), tmp, items, roomId);

    InputStream inputStream = null;
    String result = "";
    try {
      // 1. create HttpClient

      // 2. make POST request to the given URL
      HttpPost httpPost = new HttpPost(url);

      // 3. build jsonObject
      JSONObject jsonObject = new JSONObject();
      jsonObject.accumulate("head", normalQuestion.getTitle());
      jsonObject.accumulate("desc", normalQuestion.getDescription());
      jsonObject.accumulate("roomId", normalQuestion.getRoomId());
      jsonObject.accumulate("tags", new JSONArray(items));

      // 4. convert JSONObject to JSON to String
      String json = jsonObject.toString();

      // ** Alternative way to convert Person object to JSON string usin Jackson Lib
      // ObjectMapper mapper = new ObjectMapper();
      // json = mapper.writeValueAsString(person);

      // 5. set json to StringEntity
      StringEntity se = new StringEntity(json);

      // 6. set httpPost Entity
      httpPost.setEntity(se);

      // 7. Set some headers to inform server about the type of the content
      httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");
      // 8. Execute POST request to the given URL
      HttpResponse httpResponse = MainActivity.httpClient.execute(httpPost);

      // 9. receive response as inputStream
      inputStream = httpResponse.getEntity().getContent();

      // 10. convert inputstream to string
      if (inputStream != null) result = convertInputStreamToString(inputStream);
      else result = "Did not work!";
      Log.v("hehehehe", result);
    } catch (Exception e) {
      Log.d("InputStream", e.getLocalizedMessage());
    }
    return result;
  }
 /**
  * Creates a named-entity recognition request on the specified text
  *
  * @param text The text to analyze
  * @param settings The settings for the extraction
  * @return The created request
  * @throws Exception if the request cannot be created
  */
 protected HttpUriRequest createExtractionRequest(
     final String text, final Map<String, String> settings) throws Exception {
   final URI requestUrl = createExtractionRequestUrl(text);
   final HttpEntity body = createExtractionRequestBody(text, settings);
   final HttpPost request = new HttpPost(requestUrl);
   request.setHeader("Accept", "application/json");
   request.setHeader("User-Agent", "Refine NER Extension");
   request.setEntity(body);
   return request;
 }
  public String POST(String url) {

    InputStream inputStream = null;
    String result = "";
    try {

      // 1. create HttpClient
      HttpClient httpclient = new DefaultHttpClient();

      // 2. make POST request to the given URL
      HttpPost httpPost = new HttpPost(url);

      String json = "";

      // 3. build jsonObject
      JSONObject jsonObject = new JSONObject();
      jsonObject.accumulate("reg_name", name);
      jsonObject.accumulate("reg_contact", phone);
      jsonObject.accumulate("reg_veh_no", vehicle);
      jsonObject.accumulate("reg_id", regId);
      jsonObject.accumulate("reg_email", email);
      jsonObject.accumulate("lati", lati);
      jsonObject.accumulate("longi", longi);

      // 4. convert JSONObject to JSON to String
      json = jsonObject.toString();

      // 5. set json to StringEntity
      StringEntity se = new StringEntity(json);

      // 6. set httpPost Entity
      httpPost.setEntity(se);

      // 7. Set some headers to inform server about the type of the content
      httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");

      // 8. Execute POST request to the given URL
      HttpResponse httpResponse = httpclient.execute(httpPost);

      // 9. receive response as inputStream
      inputStream = httpResponse.getEntity().getContent();
      // 10. convert inputstream to string
      if (inputStream != null) {
        result = convertInputStreamToString(inputStream);

      } else result = "Did not work!";

    } catch (Exception e) {
      Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
  }
  public JSONObject postJsonObject(String url, JSONObject loginJobj) {
    InputStream inputStream = null;
    String result = "";
    try {

      // 1. create HttpClient
      HttpClient httpclient = new DefaultHttpClient();

      // 2. make POST request to the given URL

      HttpPost httpPost = new HttpPost(url);

      System.out.println(url);
      String json = "";

      // 4. convert JSONObject to JSON to String

      json = loginJobj.toString();

      System.out.println(json);
      // 5. set json to StringEntity
      StringEntity se = new StringEntity(json);

      // 6. set httpPost Entity
      httpPost.setEntity(se);

      // 7. Set some headers to inform server about the type of the content
      httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");

      // 8. Execute POST request to the given URL
      HttpResponse httpResponse = httpclient.execute(httpPost);

      // 9. receive response as inputStream
      inputStream = httpResponse.getEntity().getContent();

      // 10. convert inputstream to string
      if (inputStream != null) result = convertInputStreamToString(inputStream);
      else result = "Did not work!";

    } catch (Exception e) {
      Log.d("InputStream", e.getLocalizedMessage());
    }

    JSONObject json = null;
    try {
      json = new JSONObject(result);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    // 11. return result
    Log.d("json", String.valueOf(json));
    return json;
  }
  @Override
  public HttpUriRequest apply(String dsPrsID, String mmeAuthToken) {
    String authorization = Headers.basicToken(dsPrsID, mmeAuthToken);

    HttpPost request = new HttpPost(url);
    request.setHeader(headers.get(Headers.userAgent));
    request.setHeader(headers.get(Headers.xMmeClientInfo));
    request.setHeader("Authorization", authorization);

    return request;
  }
Пример #30
0
  public byte[] post(String postBody, String contentType) throws IOException {
    HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort());
    HttpPost httpPost = new HttpPost(uri);

    StringEntity stringEntity = new StringEntity(postBody);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    httpPost.setEntity(stringEntity);

    HttpParams params = httpPost.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClientParams.setRedirecting(params, true);
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setUserAgent(params, DEFAULT_USER_AGENT);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {

      HttpResponse response = DEFAULT_HTTP_CLIENT.execute(httpHost, httpPost);

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() >= 300)
        throw new IOException(
            "bad status code, upload file " + response.getStatusLine().getStatusCode());

      if (response.getEntity() != null) {
        response.getEntity().writeTo(baos);
      }

      body = baos.toByteArray();

      if (body == null || body.length == 0) {
        throw new IOException("invalid response");
      }

      return body;
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IOException("Http error: " + e.getMessage());
    } finally {
      try {
        baos.close();
      } catch (IOException e) {
      }
    }
  }