Exemple #1
1
    @Override
    protected String doInBackground(String... params) {

      byte[] result = null;
      String str = "";

      HttpClient client = new DefaultHttpClient();
      //            HttpGet request = new
      // HttpGet("https://backfinecar-renatdk.c9.io/api/Cars"+mSettings.getString(APP_PREFERENCES_TOKENID,"tokenId"));
      HttpGet request = new HttpGet("https://backfinecar-renatdk.c9.io/api/Cars");

      HttpResponse response;

      try {
        response = client.execute(request);
        result = EntityUtils.toByteArray(response.getEntity());
        str = new String(result, "UTF-8");
        Log.d("Response of GET request", response.toString());
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

      return str;
    }
Exemple #2
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;
  }
Exemple #3
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;
  }
  private String getBookmarkJson(String deviceID) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();

    String url = "";
    String text = null;

    try {

      URI uri = new URI("http", "www.newsd.in", "/demo1/ws/special", url, null);
      String ll = uri.toASCIIString();

      System.out.println("BookMark URL" + ll);
      HttpGet httpGet = new HttpGet(ll);

      HttpResponse response = httpClient.execute(httpGet, localContext);
      HttpEntity entity = response.getEntity();
      text = getASCIIContentFromEntity(entity);
    } catch (Exception e) {
      System.out.println("in last catch block");
      e.printStackTrace();
      return e.getLocalizedMessage();
    }
    return text;
  }
Exemple #5
0
  private String getDataStatus(String mTitle) {
    String title = mTitle;
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    System.out.println(
        Constant.WEBSERVICE_URL + Constant.WEBSERVICE_Category + "categorytitle=" + title);

    String url = "categorytitle=" + title;
    String text = null;

    try {

      URI uri = new URI("https", "www.sellyourtime.in", "/api/categories_count.php", url, null);
      String ll = uri.toASCIIString();
      HttpGet httpGet = new HttpGet(ll);

      try {
        HttpResponse response = httpClient.execute(httpGet, localContext);

        HttpEntity entity = response.getEntity();

        text = getASCIIContentFromEntity(entity);

      } catch (Exception e) {
        return e.getLocalizedMessage();
      }
    } catch (Exception e) {

    }

    return text;
  }
  @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));
  }
  /**
   * get请求
   *
   * @param context
   * @param url
   * @param params
   * @param responseListener
   * @throws IOException
   * @throws Exception
   */
  public static InputStream request(Context context, String url, Bundle params)
      throws IOException, Exception {

    if (params != null) {
      if (url.contains("?")) {
        url = url + "&" + UrlUtils.encodeUrl(params);
      } else {
        url = url + "?" + UrlUtils.encodeUrl(params);
      }
    }

    Logger.getLogger().d("GET:" + url);

    HttpGet request = new HttpGet(url);
    HttpClient httpClient = getInstance(context);

    // 解决:HttpClient WARNING: Cookie rejected: Illegal domain attribute
    httpClient
        .getParams()
        .setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    HttpResponse response;
    InputStream in = null;
    response = httpClient.execute(request);
    in = response.getEntity().getContent();

    return in;
  }
  /**
   * Get the user preferences from the GPII
   *
   * @param user
   * @return
   * @throws Exception
   */
  private String getPreferencesFromServer(EasitAccount user) throws Exception {

    HttpClient client = new DefaultHttpClient();
    HttpGet request =
        new HttpGet(
            environment.getProperty("flowManager.url")
                + environment.getProperty("flowManager.preferences"));

    // add the access token to the request header
    request.addHeader("Authorization", "Bearer " + user.getAccessToken());
    HttpResponse response = client.execute(request);

    // NOT Correct answer
    if (response.getStatusLine().getStatusCode() != 200) {
      throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    // Correct answer
    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
      result.append(line);
    }

    logger.info("User preferences:" + result);
    return result.toString();
  }
Exemple #9
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;
  }
    public JSONObject getJSONFromURL() {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);

      HttpResponse response;
      HttpClient myClient = new DefaultHttpClient();
      HttpPost myConnection = new HttpPost(urlIan);

      try {
        response = myClient.execute(myConnection);
        test = EntityUtils.toString(response.getEntity(), "UTF-8");
        arr = new JSONArray(test);
        strRoot = arr.getJSONObject(0);
        finished = true;

      } catch (IOException e) {
        // Toast.makeText(getApplicationContext(), "error1: "+e.toString(),
        // Toast.LENGTH_LONG).show();
      } catch (JSONException e) {
        // Toast.makeText(getApplicationContext(), "error2: "+e.toString(),
        // Toast.LENGTH_LONG).show();
      }

      startProgressBar();
      return strRoot;
    }
 @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 "";
 }
  /**
   * Test that a JSF web application, with xerces jar packaged within the deployment, functions
   * correctly while using the packaged xerces API.
   *
   * @throws Exception
   */
  @OperateOnDeployment("app-with-jsf")
  @Test
  public void testXercesUsageInServletInJSFApp() throws Exception {
    final HttpClient httpClient = new DefaultHttpClient();
    final String xml = "dummy.xml";

    final String requestURL =
        withJsf.toExternalForm()
            + XercesUsageServlet.URL_PATTERN
            + "?"
            + XercesUsageServlet.XML_RESOURCE_NAME_PARAMETER
            + "="
            + xml;
    final HttpGet request = new HttpGet(requestURL);
    final HttpResponse response = httpClient.execute(request);
    int statusCode = response.getStatusLine().getStatusCode();
    Assert.assertEquals("Unexpected status code", 200, statusCode);
    final HttpEntity entity = response.getEntity();
    Assert.assertNotNull("Response message from servlet was null", entity);
    final String responseMessage = EntityUtils.toString(entity);
    Assert.assertEquals(
        "Unexpected echo message from servlet",
        XercesUsageServlet.SUCCESS_MESSAGE,
        responseMessage);
  }
  @RequestMapping(
      value = {"/pay_success_url"},
      method = RequestMethod.POST)
  public void successURL(
      @RequestParam(value = "OutSum", required = true) String outSum,
      @RequestParam(value = "InvId", required = true) String invId,
      @RequestParam(value = "SignatureValue", required = true) String signatureValue,
      @RequestParam(value = "Culture", required = false) String culture)
      throws Exception {

    double _money = Double.parseDouble(outSum);
    long _id = Long.parseLong(invId);

    String md5String = md5SignatureValue(_money, _id, password2, ":Shp_item=" + shp_item);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetail = (UserDetails) auth.getPrincipal();
    Users u = userService.getRepository().findUsersByLogin(userDetail.getUsername());

    PaymentSystems ps =
        (PaymentSystems) paymentService.getRepository().findPaymentSystemsByUserId(u.getId());
    if (md5String.equals(ps.getKey())) {
      u.setSummaryCash(u.getSummaryCash() + _money);
      userService.getRepository().save(u);
    }
    HttpGet method = new HttpGet(url.concat("?OK").concat(invId));
    HttpClient client = new DefaultHttpClient();
    client.execute(method);
  }
  /**
   *
   *
   * <pre>
   * 请求标准: http://fanyi.youdao.com/openapi.do?
   * 		keyfrom=<keyfrom>&
   * 		key=<key>&
   * 		type=data&
   * 		doctype=<doctype>&
   * 		version=1.1&
   * 		q=要翻译的文本
   * 版本:1.1,请求方式:get,编码方式:utf-8
   * 主要功能:
   * 		中英互译,同时获得有道翻译结果和有道词典结果(可能没有)
   * 参数说明:
   * 		type - 返回结果的类型,固定为data
   * 		doctype - 返回结果的数据格式,xml或json或jsonp
   * 		version - 版本,当前最新版本为1.1
   * 		q - 要翻译的文本,不能超过200个字符,需要使用utf-8编码
   * 	errorCode:
   * 		0 - 正常
   * 		20 - 要翻译的文本过长
   * 		30 - 无法进行有效的翻译
   * 		40 - 不支持的语言类型
   * 		50 - 无效的key
   * </pre>
   *
   * @throws IOException
   * @throws ClientProtocolException
   */
  public static String translate(String text) throws Exception {
    String url =
        "http://fanyi.youdao.com/openapi.do?keyfrom="
            + StaticDef.KEY_FROM
            + "&key="
            + StaticDef.KEY_FOR_TRANSLATE
            + "&type=data"
            + "&doctype=json"
            + "&version=1.1"
            + "&q="
            + text;
    try {
      HttpClient client = new DefaultHttpClient();
      HttpGet httpGet = new HttpGet(url);
      HttpResponse response = client.execute(httpGet);
      InputStream is = response.getEntity().getContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(is, ENCODING));
      StringBuffer result = new StringBuffer();
      String string = null;
      if (null != (string = reader.readLine())) result.append(string).append('\n');
      // TODO parse the response json string
      String translation =
          (String) new JSONObject(result.toString()).getJSONArray("translation").get(0);

      Log.i(TAG, "result: " + result.toString());
      return translation;
    } finally {
      // close stream here
    }
  }
  @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;
    }
  }
    @Override
    public void run() {

      HttpClient httpClient = new DefaultHttpClient();
      HttpGet httpGet = new HttpGet(image_path);
      HttpResponse httpResponse = null;
      try {
        httpResponse = httpClient.execute(httpGet);
        /* Message m0 = new Message();

        m0.what=0;
        handler.sendMessage(m0);*/

        if (httpResponse.getStatusLine().getStatusCode() == 200) {
          byte[] data = EntityUtils.toByteArray(httpResponse.getEntity());
          // 获取一个Message对象,设置what为1
          Message msg = Message.obtain();
          msg.obj = data;
          msg.what = IS_FINISH;
          // 发送这个消息到消息队列中
          handler.sendMessage(msg);
          // handler.sendMessageDelayed(msg, 5000);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Exemple #17
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;
    }
    protected Void doInBackground(Void... p) {
      // 새롭게 데이터를 가져오는 부분(기존 List는 삭제)

      try {
        HttpClient httpClient = new DefaultHttpClient();
        // replace with your url
        HttpPost httpPost = new HttpPost("http://pbph.co.kr/listview.jsp");

        // Post Data
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
        nameValuePair.add(new BasicNameValuePair("boardtype", "proanswrite"));
        nameValuePair.add(new BasicNameValuePair("pagenum", num));
        nameValuePair.add(new BasicNameValuePair("writecon", writecon));

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
        HttpResponse response = httpClient.execute(httpPost);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
          returnValue = EntityUtils.toString(entity, HTTP.UTF_8);
        }

      } catch (Exception e) {
        publishProgress(-1);
        Log.e("net", "게시판 오류", e);
      }

      return null;
    }
  public String httpGetAPICall(String requestURL) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(requestURL);

    try {

      HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } else {
        Log.e(MainActivity.class.toString(), "Failedet JSON object");
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return builder.toString();
  }
  private void Login(String login, String password) {
    HttpClient httpclient = new DefaultHttpClient();
    // Prepare a request object
    StringBuilder url = new StringBuilder(getResources().getString(R.string.AUTHENTIFICATION_URL));
    url.append("?tag=login&login="******"&password="******"connection prete", response.getStatusLine().toString());

      // Get hold of the response entity

      if (response.getEntity() != null) {

        InputStream inputStream = response.getEntity().getContent();

        // Lecture du retour au format JSON
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();

        String ligneLue = bufferedReader.readLine();
        while (ligneLue != null) {
          stringBuilder.append(ligneLue + " \n");
          ligneLue = bufferedReader.readLine();
        }
        bufferedReader.close();

        // Get hold of the response entity
        JSONObject jsonObject = new JSONObject(stringBuilder.toString());

        Log.i("Chaine JSON", stringBuilder.toString());

        //	             JSONObject jsonResultSet = jsonObject.getJSONObject("nb");
        jsonObject.getJSONObject("utilisateurs").getString("mail");
        jsonObject.get("id");

        if (jsonObject.getBoolean("error") == false) {
          Intent i = new Intent(getApplicationContext(), LoggedActivity.class);
          startActivity(i);
        } else {
          Toast.makeText(getApplicationContext(), "Erreur d'identification", Toast.LENGTH_LONG)
              .show();
        }

        // If the response does not enclose an entity, there is no need
        // to worry about connection release

      }
    } catch (Exception e) {

      e.printStackTrace();
    }
  }
Exemple #21
0
    @Override
    protected JSONArray doInBackground(Map<String, String>... uri) {
      HttpClient httpclient = new DefaultHttpClient();
      HttpResponse response;
      JSONArray finalResult = null;
      try {
        response = httpclient.execute(new HttpGet(uri[0].get("host")));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {

          BufferedReader reader =
              new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
          String json = reader.readLine();
          JSONTokener tokener = new JSONTokener(json);
          try {
            finalResult = new JSONArray(tokener);
          } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }

        } else {
          // Closes the connection.
          response.getEntity().getContent().close();
          throw new IOException(statusLine.getReasonPhrase());
        }
      } catch (ClientProtocolException e) {
        // TODO Handle problems..
      } catch (IOException e) {
        // TODO Handle problems..
      }
      return finalResult;
    }
  public Document getDocument(
      double fromLatitude, double fromLongitude, GeoPoint toPosition, String mode)
      throws Exception {
    String url =
        "http://maps.googleapis.com/maps/api/directions/xml?"
            + "origin="
            + fromLatitude
            + ","
            + fromLongitude
            + "&destination="
            + toPosition.lat
            + ","
            + toPosition.lng
            + "&sensor=false&units=metric&mode="
            + mode;

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 20000); // 20seconds
    HttpConnectionParams.setSoTimeout(httpParameters, 20000); // 20 seconds

    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpPost httpPost = new HttpPost(url);
    HttpContext localContext = new BasicHttpContext();

    HttpResponse response = httpClient.execute(httpPost, localContext);

    InputStream in = response.getEntity().getContent();
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(in);
    return doc;
  }
  @Override
  public Boolean doInBackground(String... urls) {
    try {

      // ------------------>>
      HttpGet httppost = new HttpGet(urls[0]);
      HttpClient httpclient = new DefaultHttpClient();
      HttpResponse response = httpclient.execute(httppost);

      // StatusLine stat = response.getStatusLine();
      int status = response.getStatusLine().getStatusCode();
      Log.e("status", status + "");

      if (status == 200) {
        HttpEntity entity = response.getEntity();
        data = EntityUtils.toString(entity);

        return true;
      }

      // ------------------>>

    } catch (IOException e) {
      e.printStackTrace();
    }
    return false;
  }
Exemple #24
0
  public String Coment(String membre, String contenu, int lieu, float rate) throws Exception {
    String link =
        "http:"
            + Utilisateur.ip
            + "/geekAdvisorApi/avisApi.php?membre="
            + URLEncoder.encode(membre)
            + "&contenu="
            + URLEncoder.encode(contenu)
            + "&lieu="
            + lieu
            + "&rate="
            + rate
            + "";
    URL url = new URL(link);
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet();
    request.setURI(new URI(link));
    HttpResponse response = client.execute(request);
    BufferedReader in =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer sb = new StringBuffer("");
    String line = "";
    while ((line = in.readLine()) != null) {
      sb.append(line);
      break;
    }
    // jObject = new JSONObject(sb.toString());

    in.close();
    return sb.toString();
  }
Exemple #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("请求失败");
    }
  }
  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;
  }
 private String getListOrdersResponse() throws Exception {
   HttpClient client = new DefaultHttpClient();
   HttpGet get = new HttpGet(baseUri);
   HttpResponse response = client.execute(get);
   HttpEntity entity = response.getEntity();
   return getResponseString(entity);
 }
  public JSONArray getUserTimezoneHistory(
      UpdateInfo updateInfo, String api_key, OAuthConsumer consumer) throws Exception {
    long then = System.currentTimeMillis();
    String requestUrl = "http://api.bodymedia.com/v2/json/timezone?api_key=" + api_key;

    HttpGet request = new HttpGet(requestUrl);
    consumer.sign(request);
    HttpClient client = env.getHttpClient();
    enforceRateLimits(getRateDelay(updateInfo));
    HttpResponse response = client.execute(request);
    final int statusCode = response.getStatusLine().getStatusCode();
    final String reasonPhrase = response.getStatusLine().getReasonPhrase();
    if (statusCode == 200) {
      countSuccessfulApiCall(updateInfo.apiKey, updateInfo.objectTypes, then, requestUrl);
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String json = responseHandler.handleResponse(response);
      JSONObject userInfo = JSONObject.fromObject(json);
      return userInfo.getJSONArray("timezones");
    } else {
      countFailedApiCall(
          updateInfo.apiKey,
          updateInfo.objectTypes,
          then,
          requestUrl,
          "",
          statusCode,
          reasonPhrase);
      throw new Exception(
          "Error: "
              + statusCode
              + " Unexpected error trying to bodymedia timezone for user "
              + updateInfo.apiKey.getGuestId());
    }
  }
Exemple #29
0
  public static List<RoleRepresentation> getRealmRoles(HttpServletRequest req) throws Failure {
    KeycloakSecurityContext session =
        (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());

    HttpClient client = new HttpClientBuilder().disableTrustManager().build();
    try {
      HttpGet get =
          new HttpGet(
              AdapterUtils.getOriginForRestCalls(req.getRequestURL().toString(), session)
                  + "/auth/admin/realms/demo/roles");
      get.addHeader("Authorization", "Bearer " + session.getTokenString());
      try {
        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() != 200) {
          throw new Failure(response.getStatusLine().getStatusCode());
        }
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        try {
          return JsonSerialization.readValue(is, TypedList.class);
        } finally {
          is.close();
        }
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } finally {
      client.getConnectionManager().shutdown();
    }
  }
  @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());
  }