Beispiel #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;
  }
Beispiel #2
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);
         }
       }
     }
   }
 }
  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;
  }
Beispiel #4
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();
    }
  }
 @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 "";
 }
  @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";
  }
 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;
 }
Beispiel #9
0
  // create datastream
  public Datastream createDatastream(Integer feedid, Datastream datastream) throws CosmException {
    try {
      HttpPost request =
          new HttpPost(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams"
                  + JSON_FILE_EXTENSION);
      JSONObject jo = new JSONObject();
      jo.put("version", Cosm.VERSION);

      JSONArray ja = new JSONArray();
      ja.put(datastream.toJSONObject());
      jo.put("datastreams", ja);

      request.setEntity(new StringEntity(jo.toString()));
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() == 201) {
        String a[] = response.getHeaders(HEADER_PARAM_LOCATION)[0].getValue().split("/");
        String datastreamid = a[a.length - 1];
        this.client.getBody(response);
        return this.getDatastream(feedid, datastreamid);
      }

      throw new HttpException(response.getStatusLine().toString());
    } catch (Exception e) {
      e.printStackTrace();
      throw new CosmException("Caught exception in create Datastream" + e.getMessage());
    }
  }
  private String spejdPost(JsonObject jo) {
    @SuppressWarnings({"resource"})
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse resp;

    HttpPost httpPost = new HttpPost(SPEJD_SERVICE_POST);
    httpPost.addHeader("Content-Type", "application/json");

    StringEntity reqEntity = null;
    try {
      reqEntity = new StringEntity(jo.toString());
    } catch (UnsupportedEncodingException e) {
      System.out.println(e.toString());
    }

    assert reqEntity != null;

    httpPost.setEntity(reqEntity);
    try {
      resp = httpclient.execute(httpPost);
      return EntityUtils.toString(resp.getEntity());
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
  public JSONObject makeHttpRequest(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {

      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);
      // Depends on your web service
      httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
      httpPost.setEntity(new UrlEncodedFormEntity(params));
      HttpResponse httpResponse = httpClient.execute(httpPost);
      HttpEntity httpEntity = httpResponse.getEntity();
      InputStreamReader isr = new InputStreamReader(httpEntity.getContent());
      BufferedReader reader = new BufferedReader(isr);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      json = sb.toString();
    } catch (Exception e) {
      Log.e("Buffer Error", "::::Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
      jObj = new JSONObject(json);
    } catch (JSONException e) {
      Log.e("JSON Parser", "::::Error parsing data " + e.toString());
    }
    return jObj;
  }
  @Override
  protected Boolean doInBackground(File... params) {
    String server = BuildConfig.API_BASE_URL;
    ICredentials credentials = new UserCredentials(mContext);
    String url = server + "/api/nodes/" + wmID + "/photos?api_key=" + credentials.getApiKey();
    Log.d(TAG, url);

    File image = params[0];

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    try {
      MultipartEntity entity = new MultipartEntity();
      entity.addPart("photo", new FileBody(image));
      httppost.setEntity(entity);
      HttpResponse response = httpclient.execute(httppost);
      String result = EntityUtils.toString(response.getEntity());
      Log.d(TAG, result + "");
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      Log.d(TAG, e.getLocalizedMessage());
      return false;
    }
  }
  private Map<String, String> loadAllToks(final String code, int port, final HttpClient httpClient)
      throws IOException {
    final HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
    try {
      final List<? extends NameValuePair> nvps =
          Arrays.asList(
              new BasicNameValuePair("code", code),
              new BasicNameValuePair("client_id", model.getSettings().getClientID()),
              new BasicNameValuePair("client_secret", model.getSettings().getClientSecret()),
              new BasicNameValuePair("redirect_uri", OauthUtils.getRedirectUrl(port)),
              new BasicNameValuePair("grant_type", "authorization_code"));
      final HttpEntity entity = new UrlEncodedFormEntity(nvps, LanternConstants.UTF8);
      post.setEntity(entity);

      log.debug("About to execute post!");
      final HttpResponse response = httpClient.execute(post);

      log.debug("Got response status: {}", response.getStatusLine());
      final HttpEntity responseEntity = response.getEntity();
      final String body = IOUtils.toString(responseEntity.getContent());
      EntityUtils.consume(responseEntity);

      final Map<String, String> oauthToks = JsonUtils.OBJECT_MAPPER.readValue(body, Map.class);
      log.debug("Got oath data: {}", oauthToks);
      return oauthToks;
    } finally {
      post.reset();
    }
  }
  public static String invokeServer(String serverURL, String params) throws Exception {
    try {
      JSONObject jsonParams = new JSONObject(params);
      String belongProject = XcmApplication.getInstance().gettMetaData();
      jsonParams.put("belong_project", belongProject);
      LogUtil.e("gomtel", "belong_project= " + belongProject);

      params = jsonParams.toString();
      StringEntity se = new StringEntity(params);
      HttpParams paramsw = createHttpParams();
      se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
      HttpPost post = new HttpPost(serverURL);
      post.setEntity(se);
      HttpResponse response = new DefaultHttpClient(paramsw).execute(post);
      int sCode = response.getStatusLine().getStatusCode();
      if (sCode == HttpStatus.SC_OK) {
        return EntityUtils.toString(response.getEntity());
      } else {
        JSONObject json = new JSONObject();
        json.put("resultCode", -6);
        return json.toString(); // 链接不上后台
      }
    } catch (Exception e) {
      JSONObject json = new JSONObject();
      json.put("resultCode", -6);
      return json.toString(); // 链接不上后台
    }
  }
Beispiel #15
0
 // create datapoint
 public void createDatapoint(Integer feedid, String datastreamid, Datapoint datapoint)
     throws CosmException {
   try {
     HttpPost request =
         new HttpPost(
             API_BASE_URL_V2
                 + API_RESOURCE_FEEDS
                 + "/"
                 + feedid
                 + "/datastreams/"
                 + datastreamid
                 + "/datapoints"
                 + JSON_FILE_EXTENSION);
     JSONObject jo = new JSONObject();
     JSONArray ja = new JSONArray();
     ja.put(datapoint.toJSONObject());
     jo.put("datapoints", ja);
     request.setEntity(new StringEntity(jo.toString()));
     HttpResponse response = this.client.execute(request);
     StatusLine statusLine = response.getStatusLine();
     this.client.getBody(response);
     if (statusLine.getStatusCode() != 200) {
       throw new CosmException(response.getStatusLine().toString());
     }
   } catch (Exception e) {
     e.printStackTrace();
     throw new CosmException("Caught exception in create datapoint" + e.getMessage());
   }
 }
Beispiel #16
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;
  }
Beispiel #17
0
  // create datapoints
  public void createDatapoints(Integer feedid, String datastreamid, Datapoint[] datapoints)
      throws CosmException {
    try {
      HttpPost request =
          new HttpPost(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams/"
                  + datastreamid
                  + "/datapoints"
                  + JSON_FILE_EXTENSION);
      JSONObject jo = new JSONObject();

      JSONArray ja = new JSONArray();
      for (int i = 0; (i < datapoints.length); i++) {
        ja.put(datapoints[i].toJSONObject());
      }
      jo.put("datapoints", ja);
      request.setEntity(new StringEntity(jo.toString()));
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      String body = this.client.getBody(response);
      if (statusLine.getStatusCode() != 200) {
        JSONObject ej = new JSONObject(body);
        throw new CosmException(ej.getString("errors"));
      }
    } catch (Exception e) {
      throw new CosmException("Caught exception in create datapoint" + e.getMessage());
    }
  }
Beispiel #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;
 }
 // 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;
 }
Beispiel #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;
 }
  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();
    }
  }
  @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();
  }
Beispiel #23
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("请求失败");
    }
  }
 /**
  * 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();
   }
 }
  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);
  }
 @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);
   }
 }
Beispiel #27
0
    @Override
    protected String doInBackground(String... params) {
      Log.d("check", "doing in back");
      HttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost("http://84.200.84.218/flint/checkuname.php");
      List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(1);
      nameValuePairList.add(new BasicNameValuePair("uname", suname));
      HttpResponse httpResponse = null;
      try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

      try {
        httpResponse = httpClient.execute(httpPost);
        Log.d("response:", httpResponse.toString());
        // Toast.makeText(getApplicationContext(),httpResponse.toString(),Toast.LENGTH_LONG).show();
      } catch (IOException e) {
        e.printStackTrace();
      }
      String data = null;
      HttpEntity ent = httpResponse.getEntity();
      try {
        data = EntityUtils.toString(ent);
      } catch (IOException e) {
        e.printStackTrace();
      }
      Log.d("check", "doing in back done");
      return data;
    }
  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();
  }
  @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));
  }
  @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());
  }