Пример #1
1
  public String sendLoginData(LoginData data) {

    String responseMessage = null;

    try {

      System.out.println("SENDING >>>>>>>>>");

      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://system.smartsales.bg/user/android_login/");

      // Add your data
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

      nameValuePairs.add(new BasicNameValuePair("email", data.getEmail()));

      nameValuePairs.add(new BasicNameValuePair("password", data.getPassword()));

      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httppost);

      responseMessage = EntityUtils.toString(response.getEntity());

    } catch (Exception e) {
      e.printStackTrace();
    }

    return responseMessage;
  }
Пример #2
0
    protected Void doInBackground(String... params) {

      /*
       * 		Insert
       */
      try {
        HttpClient client = new DefaultHttpClient();
        String postUrl;

        postUrl = "http://naddola.cafe24.com/insertWish.php";

        HttpPost post = new HttpPost(postUrl);

        // 전달인자
        List params2 = new ArrayList();
        params2.add(new BasicNameValuePair("email", setting.getID()));
        params2.add(new BasicNameValuePair("title", myWishWeb.getTitle()));
        params2.add(new BasicNameValuePair("price", myWishWeb.getPrice() + ""));
        params2.add(new BasicNameValuePair("wish", myWishWeb.getWish() + ""));
        params2.add(new BasicNameValuePair("image", myWishWeb.getImagePath() + ""));

        UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params2, HTTP.UTF_8);
        post.setEntity(ent);
        HttpResponse responsePost = client.execute(post);
        HttpEntity resEntity = responsePost.getEntity();

      } catch (Exception e) {
        e.printStackTrace();
      }

      /*
       * 		Select
       */
      try {
        HttpClient client = new DefaultHttpClient();
        String postUrl;

        postUrl = "http://naddola.cafe24.com/getLastMyWish.php";

        HttpPost post = new HttpPost(postUrl);

        // 전달인자
        List params2 = new ArrayList();
        params2.add(new BasicNameValuePair("email", setting.getID()));

        UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params2, HTTP.UTF_8);
        post.setEntity(ent);
        HttpResponse responsePost = client.execute(post);
        HttpEntity resEntity = responsePost.getEntity();

        if (resEntity != null) {
          resp = EntityUtils.toString(resEntity);
        }

      } catch (Exception e) {
        e.printStackTrace();
      }

      return null;
    }
Пример #3
0
  /**
   * Send post to URL with parameters by given encoding.
   *
   * @param url
   * @param params
   * @param encoding
   * @return
   */
  public static String sendPost(String url, List<NameValuePair> params, String encoding) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    String content = null;
    try {
      if (url.indexOf("https") != -1) {
        httpClient = wrapClient(httpClient);
      }
      if (params != null && !params.isEmpty()) {
        try {
          if (encoding == null) {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
          } else {
            httpPost.setEntity(new UrlEncodedFormEntity(params, encoding));
          }
        } catch (UnsupportedEncodingException e) {
          log.error("Encode the parameter failed!", e);
        }
      }

      content = httpClient.execute(httpPost, new BasicResponseHandler());
    } catch (Exception e) {
      log.error("Get url faild, url: " + url, e);
      content = null;
    } finally {
      httpClient.getConnectionManager().shutdown();
    }
    return content;
  }
Пример #4
0
  // function to do the join use case
  public static void share() throws Exception {
    HttpPost method = new HttpPost(url + "/share");
    String ipAddress = null;

    Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
      NetworkInterface ni = (NetworkInterface) en.nextElement();
      if (ni.getName().equals("eth0")) {
        Enumeration<InetAddress> en2 = ni.getInetAddresses();
        while (en2.hasMoreElements()) {
          InetAddress ip = (InetAddress) en2.nextElement();
          if (ip instanceof Inet4Address) {
            ipAddress = ip.getHostAddress();
            break;
          }
        }
        break;
      }
    }

    method.setEntity(new StringEntity(username + ';' + ipAddress, "UTF-8"));
    try {
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      connIp = client.execute(method, responseHandler);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }

    // get present time
    date = new Date();
    long start = date.getTime();

    // Execute the vishwa share process
    Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp);

    String ch = "alive";
    System.out.println("Type kill to unjoin from the grid");

    while (!ch.equals("kill")) {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      ch = in.readLine();
    }

    p.destroy();

    date = new Date();
    long end = date.getTime();
    long durationInt = end - start;

    String duration = String.valueOf(durationInt);
    method = new HttpPost(url + "/shareAck");
    method.setEntity(new StringEntity(username + ";" + duration, "UTF-8"));
    try {
      client.execute(method);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }
  }
Пример #5
0
  @Override
  protected Boolean doInBackground(final String... fileNames) {
    final int n = fileNames.length / 3;
    for (i = 0; i < fileNames.length - 1; i = i + 3) {
      HttpClient httpClient = new DefaultHttpClient();
      HttpContext httpContext = new BasicHttpContext();
      String url =
          this.UPLOAD_URL
              + "?FileName="
              + URLEncoder.encode(fileNames[i])
              + "&BlobId="
              + URLEncoder.encode(fileNames[i + 2])
              + "&EntityName=t_blob";
      HttpPost httpPost = new HttpPost(url);

      try {

        CountableFileEntity entity =
            new CountableFileEntity(
                new File(fileNames[i]),
                "binary/octet-stream",
                new ProgressListener() {
                  @Override
                  public void transferred(long num) {
                    ProgressIndicator idc = new ProgressIndicator();
                    idc.progress =
                        (int) ((100.0 * i / 3 / n) + (num / (float) totalSize) * 100 / n);
                    idc.hint = "上传文件:" + fileNames[i + 1];
                    publishProgress(idc);
                  }
                });
        totalSize = entity.getContentLength();
        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost, httpContext);
        response.getEntity();

      } catch (Exception e) {
        return false;
      }
    }

    HttpPost httpPost = new HttpPost(Vault.IIS_URL + "update");
    try {
      httpPost.setEntity(new StringEntity(fileNames[fileNames.length - 1], "UTF8"));
      HttpClient httpClient = new DefaultHttpClient();
      HttpResponse response = httpClient.execute(httpPost);
      String result = EntityUtils.toString(response.getEntity(), "UTF8");
      JSONObject obj = new JSONObject(result);
      if (obj.getString("ok").equals("nok")) return false;
      else return true;
    } catch (Exception e) {
      ProgressIndicator idc = new ProgressIndicator();
      idc.progress = 100;
      idc.hint = "上传安检记录出错!";
      publishProgress(idc);
      return false;
    }
  }
Пример #6
0
  @SuppressLint("NewApi")
  public void uploadVideo(String URL, String parameter) {
    int SDK_INT = android.os.Build.VERSION.SDK_INT;

    if (SDK_INT > 8) {

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(editvideo.this);
    String user_id = preferences.getString("uid", "");
    Toast.makeText(getApplicationContext(), user_id, Toast.LENGTH_LONG).show();

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL);

    /*Toast.makeText(getApplicationContext(), "here:" + selectedImagePath,
    Toast.LENGTH_LONG).show();*/
    File file = new File(selectedImagePath);

    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {
      FormBodyPart userFile = new FormBodyPart(parameter, new FileBody(file, "video/*"));
      // userFile.addField(Environment.getExternalStorageDirectory()+"/a.png","NEWNAMEOFILE.png");
      mpEntity.addPart(userFile);
      // mpEntity.addPart("photo", new FileBody(file, "image/png"));
      mpEntity.addPart("uid", new StringBody(user_id));
      mpEntity.addPart("count", new StringBody("2"));

    } catch (Exception e) {

    }

    httppost.setEntity(mpEntity);
    HttpResponse response;
    try {
      // Log.d(TAG, "UPLOAD: about to execute");
      response = httpclient.execute(httppost);
      // /Log.d(TAG, "UPLOAD: executed");
      HttpEntity resEntity = response.getEntity();
      // Log.d(TAG, "UPLOAD: respose code: " +
      // response.getStatusLine().toString());
      // if (resEntity != null) {
      // Log.d(TAG, "UPLOAD: " + EntityUtils.toString(resEntity));
      // }
      if (resEntity != null) {
        resEntity.consumeContent();
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    httppost.setEntity(mpEntity);
  }
  /**
   * This method sends a login POST request to ensure the authentication and then send the POST
   * request with the action needed
   */
  public String loginAndExecuteBuilder(
      String URI_LOGIN,
      String URI_ACTION,
      List<NameValuePair> nameValuePairsLogin,
      List<NameValuePair> nameValuePairsAction) {
    String result = new String();
    HttpPost httppost;

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response, response_action;
    HttpEntity entity, entity_action;

    try {
      httppost = new HttpPost(URI_LOGIN);
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsLogin));
      response = httpclient.execute(httppost);

      entity = response.getEntity();
      entity.getContent();
      entity.consumeContent();

      httppost = new HttpPost(URI_ACTION);

      // Url Encoding the POST parameters
      try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsAction));
      } catch (UnsupportedEncodingException e) {
        // writing error to Log
        Log.v(
            "NetworkTools",
            "Exception executing POST: " + URI_ACTION + " Exception: " + e.toString());
      }

      // Log.v("Interoperabilty","URI para buscar  " + buildHttpHostRequest(URI_ACTION,
      // convertStreamToString(httppost.getEntity().getContent())));
      HttpPost httppost_p =
          new HttpPost(
              buildHttpHostRequest(
                  URI_ACTION, convertStreamToString(httppost.getEntity().getContent())));

      response_action = httpclient.execute(httppost_p);
      entity_action = response_action.getEntity();

      if (entity_action != null) {
        result = new String();
        result = convertStreamToString(response_action);
        entity_action.consumeContent();
      }
    } catch (Exception e) {
      Log.v(
          "NetworkTools",
          "Exception in POST request: " + URI_ACTION + " Exception: " + e.toString());
      return "";
    }
    return result;
  }
Пример #8
0
  // function to do the compute use case
  public static void compute() throws Exception {
    HttpPost method = new HttpPost(url + "/compute");

    method.setEntity(new StringEntity(username, "UTF-8"));

    try {
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      connIp = client.execute(method, responseHandler);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }

    System.out.println("Give the file name which has to be put in the grid for computation");

    // input of the file name to be computed
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String name = in.readLine();

    // get the absolute path of the current working directory
    File directory = new File(".");
    String pwd = directory.getAbsolutePath();

    // get present time
    date = new Date();
    long start = date.getTime();

    String cmd = "java -classpath " + pwd + "/vishwa/JVishwa.jar:. " + name + " " + connIp;
    System.out.println(cmd);

    // Execute the vishwa compute process
    Process p = Runtime.getRuntime().exec(cmd);

    // wait till the compute process is completed
    // check for the status code (0 for successful termination)
    int status = p.waitFor();

    if (status == 0) {
      System.out.println("Compute operation successful. Check the directory for results");
    }

    date = new Date();
    long end = date.getTime();
    long durationInt = end - start;

    String duration = String.valueOf(durationInt);
    method = new HttpPost(url + "/computeAck");
    method.setEntity(new StringEntity(username + ";" + duration, "UTF-8"));
    try {
      client.execute(method);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }
  }
  public void testSOAPCall() throws Exception {

    // test with a valid request
    HttpPost httppost = new HttpPost("http://localhost:8280/service/soap-proxy-1");
    httppost.setEntity(new StringEntity(getQuoteRequest, TEXT_XML));
    httppost.addHeader("SOAPAction", "\"urn:getQuote\"");
    HttpResponse response = client.execute(httppost);
    EntityUtils.consume(response.getEntity());
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    // test with a malformed XML
    httppost = new HttpPost("http://localhost:8280/service/soap-proxy-1");
    httppost.setEntity(new StringEntity(malformedGetQuoteRequest, TEXT_XML));
    httppost.addHeader("SOAPAction", "\"urn:getQuote\"");
    response = client.execute(httppost);
    Assert.assertEquals(
        HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode());
    Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("Validation Failed"));

    // test with a request violating schema
    httppost = new HttpPost("http://localhost:8280/service/soap-proxy-1");
    httppost.setEntity(new StringEntity(invalidQuoteRequest, TEXT_XML));
    httppost.addHeader("SOAPAction", "\"urn:getQuote\"");
    response = client.execute(httppost);
    Assert.assertEquals(
        HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode());
    Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("Validation Failed"));

    // test with CBR
    httppost = new HttpPost("http://localhost:8280/service/soap-proxy-2");
    httppost.setEntity(new StringEntity(getQuoteRequest, TEXT_XML));
    httppost.addHeader("SOAPAction", "\"urn:getQuote\"");
    response = client.execute(httppost);
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    EntityUtils.consume(response.getEntity());

    // test with CBR for a failure case
    httppost = new HttpPost("http://localhost:8280/service/soap-proxy-2");
    httppost.setEntity(new StringEntity(validQuoteRequestACP, TEXT_XML));
    httppost.addHeader("SOAPAction", "\"urn:getQuote\"");
    response = client.execute(httppost);
    Assert.assertEquals(
        HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusLine().getStatusCode());
    String responseContent = EntityUtils.toString(response.getEntity());
    System.out.println("==>" + responseContent);
    Assert.assertTrue(
        responseContent.contains(
            "Endpoint stockquote-err failed, with error code 101503 : Connect attempt to server failed"));
  }
Пример #10
0
  /**
   * Send post to URL with parameters by given encoding.
   *
   * @param url
   * @param parameterMap
   * @param encoding
   * @return
   */
  public static String sendPost(
      String url,
      Map<String, String> parameterMap,
      String encoding,
      String ip,
      boolean isBasicResHandler) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    if (ip != null) {
      httpPost.setHeader("X-Forwarded-For", ip);
    }
    // httpPost.setHeader("Host", "api.xueqiu.com");
    if (parameterMap != null && !parameterMap.isEmpty()) {
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      for (Iterator<Map.Entry<String, String>> it = parameterMap.entrySet().iterator();
          it.hasNext(); ) {
        Map.Entry<String, String> entry = it.next();
        params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
      }
      try {
        if (encoding == null) {
          httpPost.setEntity(new UrlEncodedFormEntity(params));
        } else {
          httpPost.setEntity(new UrlEncodedFormEntity(params, encoding));
        }
      } catch (UnsupportedEncodingException e) {
        log.error("Encode the parameter failed!", e);
      }
    }

    String content = null;
    try {
      if (url.indexOf("https") != -1) {
        httpClient = wrapClient(httpClient);
      }
      if (isBasicResHandler) {
        content = httpClient.execute(httpPost, new BasicResponseHandler());
      } else {
        HttpResponse httpresponse = httpClient.execute(httpPost);
        content = EntityUtils.toString(httpresponse.getEntity());
      }
    } catch (Exception e) {
      log.error("Get url faild, url: " + url, e);
      content = null;
    } finally {
      httpClient.getConnectionManager().shutdown();
    }
    return content;
  }
Пример #11
0
  public String postUser(String username) {
    String uri = "http://10.0.2.2:8090/user";
    List<NameValuePair> passParams = new ArrayList<NameValuePair>(1);
    passParams.add(new BasicNameValuePair("username", username));
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(uri);
    // Log.d("loltale:params", Integer.toString(params.length));

    try {
      httpPost.setEntity(new UrlEncodedFormEntity(passParams));
      HttpResponse response = httpClient.execute(httpPost);
      HttpEntity entity = response.getEntity();

      if (entity != null) {
        return EntityUtils.toString(entity);
      }
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Пример #12
0
 public void run() {
   HttpPost httpPost =
       new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
   //
   httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
   //
   HttpResponse response = null; // This is acting as keep alive.
   //
   while (isActive()) {
     try {
       Thread.sleep(KEEP_ALIVE_PERIOD);
       httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
       response = null;
       response = httpclient.execute(httpPost);
       int status = response.getStatusLine().getStatusCode();
       if (status != RestStreamHanlder.SUCCESS_200) {
         logger.error(
             "Cant register to the remote client, retrying in:"
                 + (KEEP_ALIVE_PERIOD / 1000)
                 + " seconds.");
         structure = registerAndGetStructure();
       }
     } catch (Exception e) {
       logger.warn(e.getMessage(), e);
     } finally {
       if (response != null) {
         try {
           response.getEntity().getContent().close();
         } catch (Exception e) {
           logger.warn(e.getMessage(), e);
         }
       }
     }
   }
 }
Пример #13
0
  public static InputStream post(Context context, String url, ArrayList<NameValuePair> params) {

    mLogger = Logger.getLogger();

    InputStream in = null;

    try {
      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, CHARSET);

      HttpPost request = new HttpPost(url);

      request.setEntity(entity);

      HttpClient client = getInstance(context);
      HttpResponse response = client.execute(request);
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

        HttpEntity resEntity = response.getEntity();

        in = (resEntity == null) ? null : resEntity.getContent();
      }
    } catch (IOException e) {

      e.printStackTrace();
      mLogger.e("error:" + e.getMessage());
    } catch (Exception e) {

      e.printStackTrace();
      mLogger.e("error:" + e.getMessage());
    }

    return in;
  }
Пример #14
0
  @Override
  protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    try {
      StringEntity se;
      // Log.e("http string",URL+"//"+send.toString());
      HttpParams httpParameters = new BasicHttpParams(); // set connection parameters
      HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);
      HttpConnectionParams.setSoTimeout(httpParameters, 60000);
      HttpClient httpclient = new DefaultHttpClient(httpParameters);
      HttpResponse response = null;
      HttpPost httppost = new HttpPost(params[0]);
      httppost.setHeader("Content-type", "application/json");
      se = new StringEntity(params[1]);
      se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
      httppost.setEntity(se);
      response = httpclient.execute(httppost);
      HttpEntity entity = response.getEntity();
      InputStream is = entity.getContent();
      streamtostring(is);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
  @Test
  public static void depositeDetailTest() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      HttpPost post = new HttpPost("http://192.168.2.111:8578/service?channel=QueryNoticePage");
      List<NameValuePair> list = new ArrayList<NameValuePair>();
      list.add(new BasicNameValuePair("platformId", "82044"));
      list.add(new BasicNameValuePair("appKey", "1"));

      post.setEntity(new UrlEncodedFormEntity(list));
      CloseableHttpResponse response = httpclient.execute(post);

      try {
        System.out.println(response.getStatusLine());
        HttpEntity entity2 = response.getEntity();
        String entity = EntityUtils.toString(entity2);
        if (entity.contains("code\":\"0")) {
          System.out.println("Success!");
          System.out.println("response content:" + entity);
        } else {
          System.out.println("Failure!");
          System.out.println("response content:" + entity);
          AssertJUnit.fail(entity);
        }
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }
  }
Пример #16
0
  @RequestMapping(value = "/kkn1234/create", method = RequestMethod.POST)
  public String formSubmit(@ModelAttribute User user, Model model)
      throws MalformedURLException, IOException {
    model.addAttribute("user", user);
    HttpPost post =
        new HttpPost(
            "http://ec2-52-4-138-196.compute-1.amazonaws.com/magento/index.php/customer/account/createpost/");
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("firstname", user.getFirstName()));
    nameValuePairs.add(new BasicNameValuePair("lastname", user.getLastName()));
    nameValuePairs.add(new BasicNameValuePair("email", user.getEmail()));
    nameValuePairs.add(new BasicNameValuePair("password", user.getPassword()));
    nameValuePairs.add(new BasicNameValuePair("confirmation", user.getConfirmation()));

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(post);
    response = httpclient.execute(post);
    System.out.println("Status code is " + response.getStatusLine().getStatusCode());
    System.out.println(response.toString());
    System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++");
    System.out.println(response.getFirstHeader("Location"));
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
    EntityUtils.consume(response.getEntity());

    /*File newTextFile = new File("C:\\Users\\Kris\\Desktop\\temp.html");
    FileWriter fileWriter = new FileWriter(newTextFile);
    fileWriter.write(response.toString());
    fileWriter.close();*/
    return "result";
  }
Пример #17
0
 public static String doPost(String url, Map<String, String> params, String jsonStr) {
   logger.info(jsonStr);
   client = getHttpClientInstance();
   URI uri = generateURLParams(url, params);
   HttpPost post = new HttpPost(uri);
   post.setConfig(requestConfig);
   String responseStr = null;
   CloseableHttpResponse httpResponse = null;
   try {
     HttpEntity entity = new StringEntity(jsonStr, DEFAULT_CHARSET);
     post.setEntity(entity);
     post.setHeader("Content-Type", "application/json");
     httpResponse = client.execute(post);
     responseStr = generateHttpResponse(httpResponse);
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (null != httpResponse) {
       try {
         httpResponse.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return responseStr;
 }
Пример #18
0
 public static String uploadMaterial(
     String url, Map<String, String> params, String formDataName, File file) {
   client = getHttpClientInstance();
   URI uri = generateURLParams(url, params);
   HttpPost post = new HttpPost(uri);
   post.setConfig(requestConfig);
   ContentBody contentBody = new FileBody(file);
   HttpEntity reqestEntity =
       MultipartEntityBuilder.create().addPart(formDataName, contentBody).build();
   post.setEntity(reqestEntity);
   String responseStr = null;
   CloseableHttpResponse httpResponse = null;
   try {
     httpResponse = client.execute(post);
     responseStr = generateHttpResponse(httpResponse);
   } catch (IOException e) {
   } finally {
     if (null != httpResponse) {
       try {
         httpResponse.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return responseStr;
 }
 @Override
 protected String doInBackground(JSONObject... params) {
   HttpClient httpClient = new DefaultHttpClient();
   JSONObject json = params[0];
   try {
     HttpPost request = new HttpPost(restfulURL);
     System.out.println("JSON DATA2 : " + json.toString());
     StringEntity entity = new StringEntity(json.toString(), "UTF-8");
     entity.setContentType("application/json");
     request.setEntity(entity);
     HttpResponse response = httpClient.execute(request);
     System.out.println("Status Code : " + response.getStatusLine());
     BufferedReader rd =
         new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
     StringBuffer sb = new StringBuffer("");
     String line = "";
     String NL = System.getProperty("line.separator");
     while ((line = rd.readLine()) != null) {
       sb.append(line + NL);
     }
     rd.close();
     return sb.toString();
   } catch (Exception e) {
     System.out.println(e.getMessage());
   }
   return "";
 }
Пример #20
0
 private HttpUriRequest createRequest(ApiRequest rawRequest) throws HttpException {
   HttpUriRequest uriRequest = null;
   String url = rawRequest.getCompleteUrl();
   switch (rawRequest.getMethod()) {
     case GET:
       uriRequest = new HttpGet(url);
       break;
     case POST:
       HttpPost post = new HttpPost(url);
       HttpEntity entity = null;
       try {
         if (rawRequest.hasFile()) {
           entity =
               createMultipartEntity(
                   rawRequest.getFileName(), rawRequest.getFile(), rawRequest.getPostParams());
         } else {
           entity = new UrlEncodedFormEntity(rawRequest.getPostParams(), HTTP.UTF_8);
         }
       } catch (IOException e) {
         throw new HttpException(e.getMessage(), e);
       }
       post.setEntity(entity);
       uriRequest = post;
       break;
   }
   setHeaders(uriRequest, rawRequest.getHeaders());
   return uriRequest;
 }
 // This method is executed in the background thread on our Survey object
 private String uploadSurveyData(String myXML) {
   // Set up communication with the server
   DefaultHttpClient client = new DefaultHttpClient();
   String result = null;
   //
   HttpPost httpPost;
   httpPost =
       new HttpPost(
           "http://YOUR DOMAIN HERE/survey-webApp/index.php/webUser_Controllers/android_controller/save_survey_xml");
   try {
     // Encode the xml, add header and set it to POST request
     StringEntity entity = new StringEntity(myXML, HTTP.UTF_8);
     // entity.setContentType("text/xml");
     httpPost.setEntity(entity);
     // Execute POST request and get response
     HttpResponse response = client.execute(httpPost);
     HttpEntity responseEntity = response.getEntity();
     // System.out.print(EntityUtils.toString(responseEntity));
     // Set up XML parsing objects
     SAXParserFactory spf = SAXParserFactory.newInstance();
     SAXParser sp = spf.newSAXParser();
     XMLReader xr = sp.getXMLReader();
     // Set up an instance of our class to parse the status response
     HttpResponseHandler myResponseHandler = new HttpResponseHandler();
     xr.setContentHandler(myResponseHandler);
     xr.parse(retrieveInputStream(responseEntity));
     // check myResponseHandler for response
     result = myResponseHandler.getStatus();
   } catch (Exception e) {
     result = "Exception - " + e.getMessage();
   }
   return result;
 }
  @Override
  public void insertOrUpdatePreferences(EasitApplicationPreferences preferences, EasitAccount user)
      throws Exception {

    // Convert the prefs to
    String strPrefs = localPrefsToServerPrefs(preferences);

    // Prepare request and send it
    DefaultHttpClient client = new DefaultHttpClient();
    StringEntity input = new StringEntity(strPrefs);
    input.setContentEncoding("UTF8");
    input.setContentType("application/json");

    HttpPost postRequest =
        new HttpPost(
            environment.getProperty("flowManager.url") + "/oldpreferences/" + user.getUserToken());
    postRequest.setEntity(input);
    HttpResponse response = client.execute(postRequest);

    // NOT Correct answer
    if (response.getStatusLine().getStatusCode() != 200) {
      logger.info("ERROR:");
      logger.info(
          "URL target"
              + environment.getProperty("flowManager.url")
              + "/oldpreferences/"
              + user.getUserToken());
      throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    // Clear connection
    client.getConnectionManager().shutdown();
  }
Пример #23
0
  public final void run() {
    proccess();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httpPost =
        new HttpPost(
            "https://api.telegram.org/bot115447632:AAGiH7bX_7dpywsXWONvsJPESQe-N7EmcQI/sendMessage");
    httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
    httpPost.addHeader("charset", "UTF-8");
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("chat_id", String.valueOf(update.message.chat.id)));
    urlParameters.add(new BasicNameValuePair("text", mensagem));
    if (teclado != null) urlParameters.add(new BasicNameValuePair("reply_markup", teclado));
    if (mensagemRetornoID != null)
      urlParameters.add(
          new BasicNameValuePair("reply_to_message_id", mensagemRetornoID.toString()));

    try {
      httpPost.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
      httpclient.execute(httpPost);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #24
0
 /**
  * POSTs the variables and returns the body
  *
  * @param url - fully qualified and encoded URL to post to
  * @param params
  * @return
  */
 public String doPost(String url, Map<String, String> params)
     throws com.ettrema.httpclient.HttpException, NotAuthorizedException, ConflictException,
         BadRequestException, NotFoundException {
   notifyStartRequest();
   HttpPost m = new HttpPost(url);
   List<NameValuePair> formparams = new ArrayList<NameValuePair>();
   for (Entry<String, String> entry : params.entrySet()) {
     formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
   }
   UrlEncodedFormEntity entity;
   try {
     entity = new UrlEncodedFormEntity(formparams);
   } catch (UnsupportedEncodingException ex) {
     throw new RuntimeException(ex);
   }
   m.setEntity(entity);
   try {
     ByteArrayOutputStream bout = new ByteArrayOutputStream();
     int res = Utils.executeHttpWithStatus(client, m, bout);
     Utils.processResultCode(res, url);
     return bout.toString();
   } catch (HttpException ex) {
     throw new RuntimeException(ex);
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   } finally {
     notifyFinishRequest();
   }
 }
Пример #25
0
  /**
   * @param url
   * @param formData 提交的数
   * @throws IOException
   */
  public static void post(String url, Map<String, Object> formData) throws Exception {
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    if (formData != null) {
      Iterator<Map.Entry<String, Object>> iterator = formData.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<String, Object> next = iterator.next();
        String key = next.getKey();
        Object value = next.getValue();
        formparams.add(new BasicNameValuePair(key, value.toString()));
      }
    }

    HttpEntity reqEntity = new UrlEncodedFormEntity(formparams, "utf-8");

    RequestConfig requestConfig =
        RequestConfig.custom()
            .setSocketTimeout(50000)
            .setConnectTimeout(50000)
            .setConnectionRequestTimeout(50000)
            .build();
    post.setEntity(reqEntity);
    post.setConfig(requestConfig);
    HttpResponse response = client.execute(post);
    if (response.getStatusLine().getStatusCode() != 200) {
      throw new Exception("请求失败");
    }
  }
Пример #26
0
 @Override
 public Object execute(Request request) {
   HttpRequestBase httpRequest = null;
   if (request.getMethod() == Request.POST) {
     HttpPost post = new HttpPost(request.getUrl());
     Object obj = request.getEntity();
     if (obj != null) {
       HttpEntity entity = null;
       if (request.isMultiPart()) {
         entity = new MultipartRequestEntity((MimeMultipart) obj);
       } else {
         try {
           entity = new StringEntity(obj.toString(), Charsets.UTF_8);
         } catch (UnsupportedCharsetException e) {
           throw new Error("Cannot encode into UTF-8", e);
         }
       }
       post.setEntity(entity);
     }
     httpRequest = post;
   } else {
     httpRequest = new HttpGet(request.getUrl());
   }
   try {
     return execute(request, httpRequest);
   } catch (RemoteException e) {
     throw e;
   } catch (Exception e) {
     throw new RuntimeException("Cannot execute " + request, e);
   }
 }
Пример #27
0
  private void initQuery() throws IOException {
    Hashtable<String, String> map = new Hashtable<String, String>();
    map.put("uid", "TEMP_USER");
    map.put("pwd", "TEMP_PASSWORD");
    map.put(QUERY_PARAM, Base64.encodeToString(TEST_QUERY.getBytes(), 0));

    HttpParams params = new BasicHttpParams();

    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, ConnectionManager.DEFAULT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, ConnectionManager.DEFAULT_TIMEOUT);
    DefaultHttpClient httpClient = new DefaultHttpClient(params);

    // create post method
    HttpPost postMethod = new HttpPost(QUERY_URI);

    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
    ObjectOutputStream objOS = new ObjectOutputStream(byteArrayOS);
    objOS.writeObject(map);
    ByteArrayEntity req_entity = new ByteArrayEntity(byteArrayOS.toByteArray());
    req_entity.setContentType(MIMETypeConstantsIF.BINARY_TYPE);

    // associating entity with method
    postMethod.setEntity(req_entity);

    // Executing post method
    executeHttpClient(httpClient, postMethod);
  }
Пример #28
0
  public static String sendToRockBlockHttp(
      String destImei, String username, String password, byte[] data)
      throws HttpException, IOException {

    CloseableHttpClient client = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost("https://secure.rock7mobile.com/rockblock/MT");
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("imei", destImei));
    urlParameters.add(new BasicNameValuePair("username", username));
    urlParameters.add(new BasicNameValuePair("password", password));
    urlParameters.add(new BasicNameValuePair("data", ByteUtil.encodeToHex(data)));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    HttpResponse response = client.execute(post);

    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
      result.append(line);
    }

    try {
      client.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result.toString();
  }
Пример #29
0
  @Test
  public void testMultipart() throws IOException, JSONException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/");

    File image = new File("resources/test/base.png");
    FileBody imagePart = new FileBody(image);
    StringBody messagePart = new StringBody("some message");

    MultipartEntity req = new MultipartEntity();
    req.addPart("image", imagePart);
    req.addPart("message", messagePart);
    httppost.setEntity(req);

    ImageEchoServer server = new ImageEchoServer(PORT);
    HttpResponse response = httpclient.execute(httppost);
    server.stop();

    HttpEntity resp = response.getEntity();
    assertThat(resp.getContentType().getValue(), is("application/json"));

    // sweet one-liner to convert an inputstream to a string from stackoverflow:
    // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string
    String out = new Scanner(resp.getContent()).useDelimiter("\\A").next();

    JSONObject json = new JSONObject(out);

    String base64 = Base64.encodeFromFile("resources/test/base.png");

    assertThat(json.getString("screenshot"), is(base64));
    assertThat(json.getBoolean("imageEcho"), is(true));
  }
Пример #30
-1
  @Test
  public void testGetAndCheckKey() throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://*****:*****@gmail.com"));
    nvps.add(new BasicNameValuePair("password", "Purbrick7"));
    post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    HttpResponse response = httpClient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();
    String responseContent = IOUtils.toString(entity.getContent());
    System.out.println(response.getFirstHeader("Content-Type"));
    System.out.println(responseContent);

    JSONObject jsonObj = (JSONObject) new JSONParser().parse(responseContent);

    HttpPost post2 = new HttpPost("http://*****:*****@gmail.com"));
    nvps2.add(new BasicNameValuePair("authKey", (String) jsonObj.get("authKey")));
    post2.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8));

    HttpResponse response2 = httpClient.execute(post2);
    assertEquals(200, response2.getStatusLine().getStatusCode());
  }