public void runSimpleLoginLoadTest() { HttpClient httpClient = getHttpClient(); // RequestEntity re = new StringRequestEntity(raw_body, "text/xml", // "UTF-16"); try { PostMethod postMethod = new PostMethod(getAsvip() + "mas/login"); postMethod.addParameters(getReqParams()); int statuscode = httpClient.executeMethod(postMethod); byte[] responseBody = postMethod.getResponseBody(); postMethod.releaseConnection(); // System.out.println(statuscode + " LOGIN RESPONSE ---- "+ new String(responseBody)); postMethod = new PostMethod(getAsvip() + "mas/logout"); statuscode = httpClient.executeMethod(postMethod); responseBody = postMethod.getResponseBody(); // System.out.println(statuscode + " LOGOUT RESPONSE ---- "+ new String(responseBody)); postMethod.releaseConnection(); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public synchronized void updateHtmlEntry(String key, String html) throws HttpException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(catalogDbURL + "update"); System.err.println(key); postMethod.addParameter("key", key); postMethod.addParameter("columns", html); try { httpClient.executeMethod(postMethod); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (postMethod.getStatusCode() == HttpStatus.SC_OK) { try { String resp = postMethod.getResponseBodyAsString(); System.err.println(resp); } catch (IOException e) { e.printStackTrace(); } } else { throw new HttpException("failed to post form."); } }
public HttpClient getAuthenticatedHttpClient( String strLogonURL, String strLogonUserId, String strLogonPassword) { HttpClient httpClient = new HttpClient(); int code = 0; if (strLogonURL != null && strLogonUserId != null && strLogonPassword != null) { PostMethod postMethod = new PostMethod(strLogonURL); postMethod.setParameter("username", strLogonUserId); postMethod.setParameter("password", strLogonPassword); postMethod.setParameter("login-form-type", "pwd"); try { code = httpClient.executeMethod(postMethod); APPLICATION_LOGGER.info("Login Http Status {} ", code); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { APPLICATION_LOGGER.error("invalid logon configurations found"); } if (code != 200) { APPLICATION_LOGGER.error("Unable to login to server, Http Status Code = {}", code); httpClient = null; } return httpClient; }
public TicketsResponse checkTickets(TicketsRequest request) { String jsonResp = null; TicketsResponse response = null; TicketsResponseError responseError = null; try { jsonResp = sendRequest(request); try { ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); response = mapper.readValue(jsonResp, TicketsResponse.class); } catch (JsonMappingException e) { // logger.error("Could not parse JSON, trying to parse an error. Original exception: ", // e); responseError = new ObjectMapper().readValue(jsonResp, TicketsResponseError.class); TicketsResponse invaildResponse = new TicketsResponse(); invaildResponse.setError(true); invaildResponse.setErrorDescription(responseError.getErrorDescription()); logger.error("UzGovUa error description: " + responseError.getErrorDescription()); return invaildResponse; } } catch (HttpException e) { e.printStackTrace(); logger.error(e.getMessage(), e); } catch (SocketTimeoutException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } return response; }
/** * Send the command to Solr using a GET * * @param queryString * @param url * @return * @throws IOException */ private static String sendGetCommand(String queryString, String url) throws IOException { String results = null; HttpClient client = new HttpClient(); GetMethod get = new GetMethod(url); get.setQueryString(queryString.trim()); client.executeMethod(get); try { // Execute the method. int statusCode = client.executeMethod(get); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + get.getStatusLine()); results = "Method failed: " + get.getStatusLine(); } results = getStringFromStream(get.getResponseBodyAsStream()); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. get.releaseConnection(); } return results; }
protected void dialImpl(String number) throws ExceptionLP { myLogger.info("Dialing <" + number + "> ..."); GetMethod method = getHttpMethod(number); try { prepareClient(client, method); int status = client.executeMethod(method); myLogger.info("Dialing done with HTTP Status: <" + status + ">"); if (status != HttpStatus.SC_OK) { byte[] responseBody = method.getResponseBody(); String s = new String(responseBody); myLogger.debug("Done dialing with response <" + s + ">"); } } catch (HttpException ex) { myLogger.debug("Got HttpException <" + ex.getMessage() + ">"); throw new ExceptionLP(EJBExceptionLP.FEHLER_TELEFON_WAHLVORGANG, ex.getMessage(), ex); } catch (IOException ex) { myLogger.debug("Got IOException <" + ex.getMessage() + ">"); throw new ExceptionLP(EJBExceptionLP.FEHLER_TELEFON_WAHLVORGANG, ex.getMessage(), ex); } finally { method.releaseConnection(); } }
/** * Call the GetMethod. * * @param url The URL for the HTTP GET method. * @return GetMethod * @throws WebserverSystemException If connection failed. */ public GetMethod get(final String url) throws RepositoryException { GetMethod get = null; try { get = new GetMethod(url); int responseCode = getHttpClient().executeMethod(get); if ((responseCode / 100) != (HTTP_RESPONSE_OK / 100)) { String message = get.getResponseBodyAsString(); if (message == null) { Header header = get.getResponseHeader("eSciDocException"); String value = header.getValue(); if (value != null) { message = "GET-Request with url " + url + " results with Exception:" + value + " ."; } else { message = "Connection to '" + url + "' failed with response code " + responseCode; } } get.releaseConnection(); log.info(message); throw new RepositoryException(message); } } catch (HttpException e) { throw new RepositoryException(e.getMessage(), e); } catch (IOException e) { throw new RepositoryException(e.getMessage(), e); } return get; }
private ClasificacionOrganizacion findRestClasificacionOrganizacion(Integer id) { HttpClient httpclient = getHttpClient(); GetMethod get = new GetMethod(restUrl.getClassOrganizacionUrl()); get.addRequestHeader("Accept", "application/xml"); ClasificacionOrganizacion ret = null; try { int result = httpclient.executeMethod(get); logger.info("Response status code: " + result); String xmlString = get.getResponseBodyAsString(); logger.info("Response body: " + xmlString); ret = importClasificacionOrganizacion(xmlString, id); } catch (HttpException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } catch (ParserConfigurationException e) { logger.error(e.getMessage()); } catch (SAXException e) { logger.error(e.getMessage()); } finally { get.releaseConnection(); } return ret; }
private Capacidad buscarCapacidad(int capacityCode) { HttpClient httpclient = getHttpClient(); GetMethod get = new GetMethod(restUrl.getCapacidadUrl()); get.addRequestHeader("Accept", "application/xml"); Capacidad ret = null; try { int result = httpclient.executeMethod(get); if (logger.isTraceEnabled()) logger.trace("Response status code: " + result); String xmlString = get.getResponseBodyAsString(); if (logger.isTraceEnabled()) logger.trace("Response body: " + xmlString); ret = importCapacidad(xmlString, capacityCode); } catch (HttpException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } catch (ParserConfigurationException e) { logger.error(e.getMessage()); } catch (SAXException e) { logger.error(e.getMessage()); } finally { get.releaseConnection(); } return ret; }
private Sector buscarSector(int sectorCode) { HttpClient httpclient = getHttpClient(); GetMethod get = new GetMethod(restUrl.getSectorUrl()); get.addRequestHeader("Accept", "application/xml"); Sector ret = null; try { int result = httpclient.executeMethod(get); logger.info("Response status code: " + result); String xmlString = get.getResponseBodyAsString(); logger.info("Response body: " + xmlString); ret = importSector(xmlString, sectorCode); } catch (HttpException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } catch (ParserConfigurationException e) { logger.error(e.getMessage()); } catch (SAXException e) { logger.error(e.getMessage()); } finally { get.releaseConnection(); } return ret; }
public static void main(String[] args) { HttpClient client = new HttpClient(); // Create an instance of HttpClient. GetMethod method = new GetMethod(url); // Create a method instance. method .getParams() .setParameter( HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler( 3, false)); // Provide custom retry handler is necessary try { int statusCode = client.executeMethod(method); // Execute the method. if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } byte[] responseBody = method.getResponseBody(); // Read the response body. System.out.println( new String( responseBody)); // Deal with the response.// Use caution: ensure correct character // encoding and is not binary data } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { method.releaseConnection(); // Release the connection. } }
public static String postXml(String url, String xml) { String txt = null; PostMethod post = new PostMethod(url); // 请求地址 post.setRequestBody(xml); // 这里添加xml字符串 // 指定请求内容的类型 post.setRequestHeader("Content-type", "text/xml; charset=iso-8859-1"); HttpClient httpclient = new HttpClient(); // 创建 HttpClient 的实例 int result; try { result = httpclient.executeMethod(post); System.out.println("Response status code: " + result); // 返回200为成功 System.out.println("Response body: "); BufferedReader reader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), "ISO-8859-1")); String tmp = null; String htmlRet = ""; while ((tmp = reader.readLine()) != null) { htmlRet += tmp + "\r\n"; } txt = new String(htmlRet.getBytes("ISO-8859-1"), "UTF-8"); System.out.println(txt); // txt = post.getResponseBodyAsString(); // System.out.println(post.getResponseBodyAsString());// 返回的内容 post.releaseConnection(); // 释放连接 } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return txt; }
public static Boolean urlIsTrue(String id) { String uri = "http://" + PostUrl.Media + ":8080/upload/" + id + ".jpg"; HttpClient client = new HttpClient(); client.getParams().setContentCharset("utf-8"); client.getParams().setSoTimeout(10000); client .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); GetMethod getMethod = new GetMethod(uri); System.out.println("1"); try { if (client.executeMethod(getMethod) == HttpStatus.SC_OK) { return true; } } catch (HttpException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } finally { getMethod.releaseConnection(); } System.out.println("图片下载不了"); return false; }
public void test_getTagsFolder() { try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } String response_body = ""; HttpMethod get_col_tags = new GetMethod( SLING_URL + COLLECTION_URL + slug + "/" + TAGS_FOLDER + "/" + "sling:resourceType"); try { client.executeMethod(get_col_tags); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { response_body = get_col_tags.getResponseBodyAsString(); } catch (IOException e) { e.printStackTrace(); } assertEquals(response_body, TAGS_RESOURCE_TYPE); get_col_tags.releaseConnection(); }
public static Bitmap readImg(String id) { String uri = "http://" + PostUrl.Media + ":8080/upload/" + id + ".jpg"; HttpClient client = new HttpClient(); client.getParams().setContentCharset("utf-8"); client.getParams().setSoTimeout(10000); client .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); GetMethod getMethod = new GetMethod(uri); System.out.println("1"); try { if (client.executeMethod(getMethod) == HttpStatus.SC_OK) { System.out.println("2"); InputStream inputStream = getMethod.getResponseBodyAsStream(); System.out.println("3"); Bitmap img = BitmapFactory.decodeStream(inputStream); inputStream.close(); return img; } } catch (HttpException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } finally { getMethod.releaseConnection(); } System.out.println("图片下载不了"); return null; }
private static boolean createRepo( final String scmUrl, final String password, final String repository) { HttpClient client = new HttpClient(); String uri = scmUrl + API + "/projects"; LOGGER.debug("Create Repo: {}", uri); PostMethod post = new PostMethod(uri); post.setParameter("name", repository); post.setParameter("private_token", password); try { int result = client.executeMethod(post); LOGGER.info("Return code: " + result); for (Header header : post.getResponseHeaders()) { LOGGER.info(header.toString().trim()); } LOGGER.info(post.getResponseBodyAsString()); } catch (HttpException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { post.releaseConnection(); } return true; }
private String doCall(String uri) throws IOException { System.out.println("We're calling the uri"); HttpClient httpClient = new HttpClient(); httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); HttpMethod getMethod = new GetMethod(uri); try { int response = httpClient.executeMethod(getMethod); if (response != 200) { throw new IOException("HTTP problem, httpcode: " + response); } InputStream stream = getMethod.getResponseBodyAsStream(); String responseText = responseToString(stream); return responseText; } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
private String getXmlToken() { String token = null; HttpClient httpclient = getHttpClient(); GetMethod get = new GetMethod(restUrl.getTokenUrl()); get.addRequestHeader("Accept", "application/xml"); NameValuePair userParam = new NameValuePair(USERNAME_PARAM, satelite.getUser()); NameValuePair passwordParam = new NameValuePair(PASSWORD_PARAM, satelite.getPassword()); NameValuePair[] params = new NameValuePair[] {userParam, passwordParam}; get.setQueryString(params); try { int statusCode = httpclient.executeMethod(get); if (statusCode != HttpStatus.SC_OK) { logger.error("Method failed: " + get.getStatusLine()); } token = parseToken(get.getResponseBodyAsString()); } catch (HttpException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } catch (ParserConfigurationException e) { logger.error(e.getMessage()); } catch (SAXException e) { logger.error(e.getMessage()); } finally { get.releaseConnection(); } return token; }
public void test_getContentsFolder() { try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } // Get the content HttpMethod get_col_contents = new GetMethod( SLING_URL + COLLECTION_URL + slug + "/" + CONTENTS_FOLDER + "/" + "sling:resourceType"); try { client.executeMethod(get_col_contents); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // handle response. String response_body = ""; try { response_body = get_col_contents.getResponseBodyAsString(); } catch (IOException e) { e.printStackTrace(); } assertEquals(response_body, CONTENTS_RESOURCE_TYPE); }
public void testWriteRequestReleaseConnection() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(1); client.setHttpConnectionManager(connectionManager); GetMethod get = new GetMethod("/") { protected boolean writeRequestBody(HttpState state, HttpConnection conn) throws IOException, HttpException { throw new IOException("Oh no!!"); } }; try { client.executeMethod(get); fail("An exception should have occurred."); } catch (HttpException e) { e.printStackTrace(); fail("HttpException should not have occurred: " + e); } catch (IOException e) { // expected } try { connectionManager.getConnectionWithTimeout(client.getHostConfiguration(), 1); } catch (ConnectTimeoutException e) { e.printStackTrace(); fail("Connection was not released: " + e); } }
protected void loadNetImage() { String url = "http://ww2.sinaimg.cn/thumbnail/675e5a2bjw1e0pydwgwgnj.jpg"; HttpClient httpClient = null; GetMethod httpGet = null; Bitmap bitmap = null; try { httpClient = getHttpClient(); httpGet = getHttpGet(url, null, null); if (httpClient.executeMethod(httpGet) == HttpStatus.SC_OK) { InputStream inStream = httpGet.getResponseBodyAsStream(); bitmap = BitmapFactory.decodeStream(inStream); inStream.close(); mImageView03.setImageBitmap(bitmap); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpGet.releaseConnection(); httpClient = null; } }
public Map<String, String> read(String in) { List<String> result = new ArrayList<String>(); HttpClient client = new HttpClient(); // client.getHostConfiguration().setProxy("wwwcache.open.ac.uk", 80); ModelFactory modelFactory = RDF2Go.getModelFactory(); Model model = modelFactory.createModel(); String serviceEndPoint = "http://ws.geonames.org/search?q=" + "London" + "&type=rdf"; GetMethod geoNameSearch = new GetMethod(serviceEndPoint); String rdf = ""; try { client.executeMethod(geoNameSearch); rdf = geoNameSearch.getResponseBodyAsString(); String rdf8 = new String(rdf.getBytes(), "UTF-8"); System.out.println(rdf8); String modelQueryString = "SELECT DISTINCT ?name ?country ?location ?map ?lat ?long WHERE { ?location <http://www.geonames.org/ontology#name> ?name ." + "?location <http://www.geonames.org/ontology#locationMap> ?map ." + "?location <http://www.geonames.org/ontology#countryCode> ?country ." + "?location <http://www.w3.org/2003/01/geo/wgs84_pos#lat> ?lat ." + "?location <http://www.w3.org/2003/01/geo/wgs84_pos#long> ?long}"; model.open(); model.readFrom(new ByteArrayInputStream(rdf8.getBytes())); QueryResultTable results = model.sparqlSelect(modelQueryString); System.out.println(results.toString()); ClosableIterator<QueryRow> iter = results.iterator(); while (iter.hasNext()) { QueryRow row = iter.next(); String name = row.getValue("name").toString(); String country = row.getValue("country").toString(); String location = row.getValue("location").toString(); String map = row.getValue("location").toString(); String lat = row.getValue("lat").toString(); String longatti = row.getValue("long").toString(); result.add( name + " -> " + country + ";" + location + ";" + lat + ";" + longatti + ";" + name + ";" + name + ":" + country + ":" + location + ":" + map); } } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } model.close(); // return result; return null; }
/** * 获取网络图片 * * @param url * @return */ public static Bitmap getBitmapByNet(String url) throws AppException { // System.out.println("image_url==> "+url); URI uri = null; try { uri = new URI(url, false, "UTF-8"); } catch (URIException e) { e.printStackTrace(); } if (uri != null) url = uri.toString(); HttpClient httpClient = null; GetMethod httpGet = null; Bitmap bitmap = null; int time = 0; do { try { httpClient = HttpHelper.getHttpClient(); httpGet = HttpHelper.getHttpGet(url, HttpHelper.getUserAgent()); int statusCode = httpClient.executeMethod(httpGet); if (statusCode != HttpStatus.SC_OK) { throw AppException.http(statusCode); } InputStream inStream = httpGet.getResponseBodyAsStream(); bitmap = BitmapFactory.decodeStream(inStream); inStream.close(); break; } catch (HttpException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // 发生致命的异常,可能是协议不对或者返回的内容有问题 e.printStackTrace(); throw AppException.http(e); } catch (IOException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // 发生网络异常 e.printStackTrace(); throw AppException.network(e); } finally { // 释放连接 httpGet.releaseConnection(); } } while (time < RETRY_TIME); return bitmap; }
public static void main(String[] args) { // (1)构造HttpClient的实例 HttpClient httpClient = new HttpClient(); // (2)创建POST方法的实例 PostMethod postMethod = new PostMethod("http://10.3.75.203:9080/ESB/appleServie?serviceCode=authentication"); // GetMethod getMethod = new GetMethod("http://*****:*****@apple.com\",\"password\": \"Apple1234\", \"shipTo\":\"863348\",\"langCode\":\"en\",\"timeZone\":\"420\"}"; postMethod.setRequestHeader("http.default-headers", authenticateText); // 使用系统提供的默认的恢复策略 postMethod .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); try { postMethod.setRequestEntity( new StringRequestEntity(authenticateText, "text/xml; charset=UTF-8", "UTF-8")); // (4)执行postMethod int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + postMethod.getStatusLine()); } // (5)读取response头信息 // Header headerResponse = postMethod // .getResponseHeader("response_key"); // String headerStr = headerResponse.getValue(); // (6)读取内容 byte[] responseBody = postMethod.getResponseBody(); // (7) 处理内容 // System.out.println(headerStr); System.out.println("返回的内容信息:" + new String(responseBody, "UTF-8")); } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问题 System.out.println("Please check your provided http address!"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // 释放连接 postMethod.releaseConnection(); } }
// @Scheduled(cron = "1 0/5 * * * *") private void refreshCookie() { resetMethod(); try { httpMethod.setPath("/"); httpClient.executeMethod(httpMethod); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * 获取用户的主页 * * @param client * @param homePageUrl * @throws IOException */ public static void getHomePage(HttpClient client, String homePageUrl) throws IOException { // TODO Auto-generated method stub GetMethod get = new GetMethod(homePageUrl); try { client.executeMethod(get); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String response = get.getResponseBodyAsString(); System.out.println(response); }
@org.junit.Test public void test_crossdomain_url() { HttpMethod get = new GetMethod(SLING_URL + CROSSDOMAIN_URL); try { client.executeMethod(get); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } assertTrue((get.getStatusCode() != 403)); }
public static String HttpPost(String url, String method, Map parmMap) throws Exception { String encoding = "UTF-8"; String webUrl = url + "/" + method; if (encoding == null || "".equals(encoding)) encoding = "UTF-8"; StringBuffer sBuffer = new StringBuffer(); // 构造HttpClient的实例 HttpClient httpClient = new HttpClient(); // 创建POS方法的实例 NameValuePair[] pairs = null; PostMethod postMethod = new PostMethod(webUrl); if (parmMap != null) { pairs = new NameValuePair[parmMap.size()]; Set set = parmMap.keySet(); Iterator it = set.iterator(); int i = 0; while (it.hasNext()) { Object key = it.next(); Object value = parmMap.get(key); pairs[i] = new NameValuePair(key.toString(), value.toString()); i++; } postMethod.setRequestBody(pairs); } postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding); try { // 执行getMethod int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + postMethod.getStatusLine()); } InputStream resStream = postMethod.getResponseBodyAsStream(); sBuffer = new StringBuffer(postMethod.getResponseBodyAsString() + ""); // modify by guanshiqiang at 2012-06-01 for 处理接收字符乱码bug end // 处理内容 // sBuffer.append(new String(responseBody,encoding)); } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问题 System.out.println("Please check your provided http address!"); e.printStackTrace(); throw e; } catch (IOException e) { e.printStackTrace(); throw e; } finally { // 释放连接 postMethod.releaseConnection(); } return sBuffer.toString(); }
public static String get(String url) { HttpMethod method = new GetMethod(url); try { int returnCode = client.executeMethod(method); if ((returnCode >= 200) && (returnCode < 300)) { return method.getResponseBodyAsString(); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
public static String HttpPostForLogistics(String url, String method, String str) { String encoding = "UTF-8"; String webUrl = url + "/" + method; StringBuffer sBuffer = new StringBuffer(); // 构造HttpClient的实例 HttpClient httpClient = new HttpClient(); // 创建POS方法的实例 PostMethod postMethod = new PostMethod(webUrl); try { // postMethod.setRequestEntity(new ByteArrayRequestEntity(str.getBytes(),"application/json; // charset=utf-8")); postMethod.setRequestBody(str); } catch (Exception e1) { e1.printStackTrace(); } postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000); // 连接5秒超时 httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000); // 读取30秒超时 // postMethod.setRequestHeader("Content-type", "application/json; charset=utf-8"); // postMethod.setDoAuthentication(false); // postMethod.addRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT // 5.1)"); postMethod.setDoAuthentication(true); postMethod.addRequestHeader("Authorization", "Basic U0FQX0FNOkFubmllTWFvMTIzNA=="); postMethod.setRequestHeader("Content-type", "application/json"); try { // 执行getMethod int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + postMethod.getStatusLine()); sBuffer = new StringBuffer(); } else { sBuffer = new StringBuffer(postMethod.getResponseBodyAsString() + ""); } } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问题 System.out.println("Please check your provided http address!"); e.printStackTrace(); } catch (IOException e) { // 发生网络异常 e.printStackTrace(); } finally { // 释放连接 postMethod.releaseConnection(); } return sBuffer.toString(); }