private String doGet(String url) { String responseStr = ""; try { HttpGet httpRequest = new HttpGet(url); HttpParams params = new BasicHttpParams(); ConnManagerParams.setTimeout(params, 1000); HttpConnectionParams.setConnectionTimeout(params, 3000); HttpConnectionParams.setSoTimeout(params, 5000); httpRequest.setParams(params); HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); final int ret = httpResponse.getStatusLine().getStatusCode(); if (ret == HttpStatus.SC_OK) { responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8); } else { responseStr = "-1"; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return responseStr; }
public String call(String url, Map<String, String> fields) { // create an HTTP request to a protected resource HttpGet request = new HttpGet(endpoint); HttpParams p = new BasicHttpParams(); for (Entry<String, String> en : fields.entrySet()) { p.setParameter(en.getKey(), en.getValue()); } request.setParams(p); // sign the request try { consumer2.sign(request); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } // send the request HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(request); return convertStreamToString(response.getEntity().getContent()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
/** * @param request * @return */ public static HttpGet convertToHttpGet(HttpRequest request) { HttpGet get = null; get = new HttpGet(request.getRequestLine().getUri()); get.setHeaders(request.getAllHeaders()); get.setParams(request.getParams()); return get; }
private void doGet() { try { /* * [ Set Url Parameters ] */ if (params != null) { Iterator it = params.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = URLEncoder.encode(params.get(key), AppConf.APP_WEB_SERVER_ENCODING); if (url.indexOf("?") == -1) { url = url + "?" + key + "=" + value; } else { url = url + "&" + key + "=" + value; } } } Logger.i(url); /* * [ Create Http Objects ] */ HttpGet httpGet = new HttpGet(url); DefaultHttpClient client = new DefaultHttpClient(); /* * [ Set Properties ] */ // httpGet.setHeader("Connection", "Keep-Alive"); /* * [ Set Http Default Params ] */ BasicHttpParams httpParams = new BasicHttpParams(); httpGet.setParams(httpParams); /* * [ Execute Request ] */ HttpResponse response = client.execute(httpGet, responseHandler); /* * [ Check Status ] */ int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { responseHandler.onComplete(Integer.toString(status), response); } else { responseHandler.onError(Integer.toString(status), response); } } catch (Exception e) { Logger.e( "!!!!!!!!!!!!!!!! ---------------------- GetMethodRequestObject Method Error ---------------------- !!!!!!!!!!!!!!!!" + e.getMessage() + e.toString()); } }
@Override protected Map<String, List<String>> doInBackground(List<FormField>... params) { String attUrl = client .getClientInfo() .resolveUrl("/services/apexrest/MobilePickListValuesWebService?fieldId=") .toString(); for (FormField fieldId : params[0]) { HttpClient tempClient = new DefaultHttpClient(); URI theUrl = null; try { theUrl = new URI(attUrl + fieldId.getId()); HttpGet getRequest = new HttpGet(); getRequest.setURI(theUrl); getRequest.setHeader("Authorization", "Bearer " + client.getAuthToken()); BasicHttpParams param = new BasicHttpParams(); // param.setParameter("fieldId", fieldId); getRequest.setParams(param); HttpResponse httpResponse = null; try { httpResponse = tempClient.execute(getRequest); StatusLine statusLine = httpResponse.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity); JSONObject jo = null; try { jo = new JSONObject(result); } catch (JSONException e) { e.printStackTrace(); } JSONArray ja = null; try { ja = jo.getJSONArray(parameters.get("auth")); fieldId.setPicklistEntries(convertJsonStringToString(ja)); } catch (JSONException e) { e.printStackTrace(); } } } else { httpResponse.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (IOException e) { e.printStackTrace(); } } catch (URISyntaxException e) { e.printStackTrace(); } } return null; }
private JSONObject Get(String url) throws ClientProtocolException, IOException, IllegalStateException, JSONException { HttpGet req = new HttpGet(url); HttpParams params = new BasicHttpParams(); params.setParameter("http.protocol.handle-redirects", false); req.setParams(params); HttpResponse response = client.execute(req); JSONObject result = new JSONObject(convertToString(response.getEntity().getContent())); return result; }
/** * 调用的时候要判断是否为空 * * @param model * @return */ public static Object get(RequestModel model) { // Authenticator.setDefault(new Authenticator() { // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication (Loggerin, password.toCharArray()); // } // }); DefaultHttpClient client = new DefaultHttpClient(); String url = model.host.concat(model.context.getString(model.requestUrl)); StringBuffer sb = new StringBuffer(); sb.append(url); String afterSign = addGetParams(model.requestDataMap); sb.append(afterSign); Logger.e("get请求方法", "最后的请求地址是 == " + sb.toString()); String u = sb.toString(); u = u.replace(" ", "%20"); HttpGet get = new HttpGet(u); get.setHeader( "Authorization", "Basic " + Base64.encodeToString((Loggerin + ":" + password).getBytes(), Base64.NO_WRAP)); HttpParams params = new BasicHttpParams(); params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 8000); HttpConnectionParams.setSoTimeout(params, 8000); get.setParams(params); Object obj = null; try { HttpResponse response = client.execute(get); if (response == null) { Logger.e("get", "response == null"); } if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity(), "UTF-8"); Logger.i(NetUtil.class.getSimpleName() + "get3", result); try { obj = model.jsonParser.parseJSON(result); } catch (JSONException e) { Log.e(NetUtil.class.getSimpleName() + "4", e.getLocalizedMessage(), e); } return obj; } } catch (Exception e) { e.printStackTrace(); } return null; }
// This method for GET public String getHttp(String url) { BufferedReader reader = null; StringBuilder builder = new StringBuilder(); HttpGet get = new HttpGet(url); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setUseExpectContinue(params, false); get.setParams(params); try { HttpResponse response = client.execute(get); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); String codeStatus = String.valueOf(statusCode); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } Log.d("Status Code", codeStatus); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } } return builder.toString(); }
/** * Requests given URL and returns redirect location URL from response header. If response is not * redirected then returns the same URL which was requested * * @param URL url to which the request should be made * @param DefaultHttpClient httpClient to test multiple access * @return URL redirect location * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ public static URL makeCallWithoutRedirect(URL url, DefaultHttpClient httpClient) throws ClientProtocolException, IOException, URISyntaxException { HttpParams params = new BasicHttpParams(); params.setParameter(ClientPNames.HANDLE_REDIRECTS, false); String redirectLocation = url.toExternalForm(); HttpGet httpGet = new HttpGet(url.toURI()); httpGet.setParams(params); HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); LOGGER.info("Request to: " + url + " responds: " + statusCode); Header locationHeader = response.getFirstHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); } HttpEntity entity = response.getEntity(); if (entity != null) { EntityUtils.consume(entity); } return new URL(redirectLocation); }
public static void setParameter(HttpGet get) { get.setParams(HTTPBuilder.getHttpParams()); }
/* * the doInBackground function does the actual background processing * * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected JSONObject doInBackground(Void... params) { JSONObject errorResponse = null; Log.d(TAG, "Started logo request via " + serviceUri); Log.d(TAG, "Using MCC=" + mcc); Log.d(TAG, "Using MNC=" + mnc); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(enableCookies != null ? enableCookies.booleanValue() : false); Log.d(TAG, "Allowing cookies = " + cookieManager.acceptCookie()); /* * sets up the HTTP request with a redirect_uri parameter - in practice * we're looking for mcc/mnc added to the redirect_uri if this step is necessary */ String requestUri = serviceUri; requestUri = HttpUtils.addUriParameter(requestUri, "logosize", logosize); /* * if there are Mobile Country Code and Mobile Network Code values add * as HTTP headers */ if (mcc != null && mnc != null) { requestUri = requestUri + "&mcc_mnc=" + mcc + "_" + mnc; } else { requestUri = requestUri + "&mcc_mnc=_"; } HttpGet httpRequest = new HttpGet(requestUri); httpRequest.addHeader("Accept", "application/json"); if (sourceIP != null) { httpRequest.addHeader("x-source-ip", sourceIP); } try { // TODO -workaround SSL errors HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); registry.register(new Scheme("https", socketFactory, 443)); HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); /* * get an instance of an HttpClient, the helper makes sure HTTP * Basic Authorization uses the consumer Key */ HttpClient httpClient = HttpUtils.getHttpClient(); HttpParams httpParams = httpRequest.getParams(); httpParams.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE); httpRequest.setParams(httpParams); /* * send the HTTP POST request and get the response */ Log.d(TAG, "Making " + httpRequest.getMethod() + " request to " + httpRequest.getURI()); HttpResponse httpResponse = httpClient.execute(httpRequest); Log.d(TAG, "Request completed with status=" + httpResponse.getStatusLine().getStatusCode()); /* * obtain the headers from the httpResponse. Content-Type and * Location are particularly required */ HashMap<String, String> headerMap = HttpUtils.getHeaders(httpResponse); Log.d(TAG, "headerMap =" + headerMap); String contentType = headerMap.get("content-type"); String location = headerMap.get("location"); /* * the status code from the HTTP response is also needed in * processing */ int statusCode = httpResponse.getStatusLine().getStatusCode(); Log.d( TAG, "status=" + statusCode + " CT=" + contentType + " Loc=" + location + " JSON?" + HttpUtils.isJSON(contentType) + " HTML?" + HttpUtils.isHTML(contentType)); /* * process a HTTP 200 (OK) response */ if (statusCode == HttpStatus.SC_OK) { /* * if the response content type is json this will contain the * endpoint information */ if (HttpUtils.isJSON(contentType)) { String logoResponse = HttpUtils.getContentsFromHttpResponse(httpResponse); Log.d(TAG, "Converting logo data " + logoResponse); Object json = JsonUtils.convertContent(logoResponse, contentType); LogoResponseArray logos = new LogoResponseArray(json); Log.d( TAG, "Have logo information " + logos + " # elemenst = " + ((logos != null && logos.getLogos() != null) ? logos.getLogos().length : 0)); if (logos != null && logos.getLogos() != null) { for (int i = 0; i < logos.getLogos().length; i++) { Log.d(TAG, "URL[" + i + "] = " + logos.getLogos()[i].getUrl()); LogoCache.addLogoResponse(logos.getLogos()[i]); } } } /* * HTTP status code 302 is a redirect - there should also be a * location header */ /* * any HTTP status code 400 or above is an error */ } else if (statusCode >= HttpStatus.SC_BAD_REQUEST) { /* * read the contents of the response body */ HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = httpEntity.getContent(); String contents = HttpUtils.getContentsFromInputStream(is); /* * if the response content type is JSON return as the error */ if (HttpUtils.isJSON(contentType)) { Object rawJSON = JsonUtils.convertContent(contents, contentType); if (rawJSON != null && rawJSON instanceof JSONObject) { errorResponse = (JSONObject) rawJSON; } } else { /* * non JSON data - just return the HTTP status code */ errorResponse = JsonUtils.simpleError("HTTP " + statusCode, "HTTP " + statusCode); } } // is this request a redirection? /* * convert the various internal error types to displayable errors */ } catch (UnsupportedEncodingException e) { errorResponse = JsonUtils.simpleError( "UnsupportedEncodingException", "UnsupportedEncodingException - " + e.getMessage()); } catch (ClientProtocolException e) { Log.d(TAG, "ClientProtocolException=" + e.getMessage()); errorResponse = JsonUtils.simpleError( "ClientProtocolException", "ClientProtocolException - " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "IOException=" + e.getMessage()); errorResponse = JsonUtils.simpleError("IOException", "IOException - " + e.getMessage()); } catch (JSONException e) { Log.d(TAG, "JSONException=" + e.getMessage()); errorResponse = JsonUtils.simpleError("JSONException", "JSONException - " + e.getMessage()); } return errorResponse; }