Java Code Examples for org.apache.http.impl.client.DefaultHttpClient.execute()

The following are Jave code examples for showing how to use execute() of the org.apache.http.impl.client.DefaultHttpClient class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: order-by-android   File: DownloadNotas.java   View Source Code Vote up 6 votes
@Override
protected List<String> doInBackground(String... url) {
    List<String> jsons = new ArrayList<String>();
    //Laço de repetição que percorre os quatro bimestres
    for(int i=0;i<4;i++) {
        //Instancia um cliente http, que fará a requisição do json
        DefaultHttpClient lHttpClient = new DefaultHttpClient();
        //Define um HttpGet, que contém a url
        HttpGet lHttpGet = new HttpGet(url[0].replace("$rm", mAluno).replace("$bim",String.valueOf(i+1)));
        try {
            //Executa e obtem a resposta da página da API
            HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet);
            //Lê o resultado
            BufferedReader reader = new BufferedReader(new InputStreamReader(lHttpResponse.getEntity().getContent(), "UTF-8"));

            jsons.add(reader.readLine());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return jsons;
}
 
Example 2
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View Source Code Vote up 6 votes
public static void setPathRangeIndexInDatabase(String dbName, JsonNode jnode) throws IOException
{
	try {			
		DefaultHttpClient client = new DefaultHttpClient();
		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));
		
			HttpPut put = new HttpPut("http://"+host+":8002"+ "/manage/v2/databases/"+dbName+"/properties?format=json");
			put.addHeader("Content-type", "application/json");
			put.setEntity(new StringEntity(jnode.toString()));

			HttpResponse response = client.execute(put);
			HttpEntity respEntity = response.getEntity();
			if(respEntity != null){
				String content =  EntityUtils.toString(respEntity);
				System.out.println(content);
			}
		}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}
}
 
Example 3
Project: sjk   File: CatalogConvertorControllerTest.java   View Source Code Vote up 6 votes
@Test
public void testEditList() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/catalogconvertor/edit.list.d";
    URIBuilder urlb = new URIBuilder(url);

    // 参数
    urlb.setParameter("id", "1,2");
    urlb.setParameter("marketName", "eoemarket,eoemarket");
    urlb.setParameter("catalog", "1,1");
    urlb.setParameter("subCatalog", "15,8");
    urlb.setParameter("subCatalogName", "系统工具,生活娱乐1");
    urlb.setParameter("targetCatalog", "1,1");
    urlb.setParameter("targetSubCatalog", "14,9");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
 
Example 4
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View Source Code Vote up 6 votes
public static void deleteRESTUser(String usrName){
	try{
		DefaultHttpClient client = new DefaultHttpClient();

		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));

		HttpDelete delete = new HttpDelete("http://"+host+":8002/manage/v2/users/"+usrName);

		HttpResponse response = client.execute(delete);
		if(response.getStatusLine().getStatusCode()== 202){
			Thread.sleep(3500);
		}
	}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}

}
 
Example 5
Project: sjk   File: CatalogConvertorControllerTest.java   View Source Code Vote up 6 votes
@Test
public void testEdit() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/catalogconvertor/edit.json";
    URIBuilder urlb = new URIBuilder(url);

    // 参数
    urlb.setParameter("id", "1");
    urlb.setParameter("marketName", "eoemarket");
    urlb.setParameter("catalog", "1");
    urlb.setParameter("subCatalog", "15");
    urlb.setParameter("subCatalogName", "系统工具1");
    urlb.setParameter("targetCatalog", "1");
    urlb.setParameter("targetSubCatalog", "14");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
 
Example 6
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View Source Code Vote up 6 votes
public static void setAuthentication(String level,String restServerName) throws ClientProtocolException, IOException
{
	DefaultHttpClient client = new DefaultHttpClient();

	client.getCredentialsProvider().setCredentials(
			new AuthScope(host, 8002),
			new UsernamePasswordCredentials("admin", "admin"));
	String  body = "{\"authentication\": \""+level+"\"}";

	HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default");
	put.addHeader("Content-type", "application/json");
	put.setEntity(new StringEntity(body));

	HttpResponse response2 = client.execute(put);
	HttpEntity respEntity = response2.getEntity();
	if(respEntity != null){
		String content =  EntityUtils.toString(respEntity);
		System.out.println(content);
	}
}
 
Example 7
Project: sjk   File: ControllerTest.java   View Source Code Vote up 6 votes
@Test
public void testbrokenLink() throws IOException, URISyntaxException {

    JSONObject object = new JSONObject();
    object.put("key", "sprSCKKWf8xUeXxEo6Bv0lE1sSjWRDkO");
    object.put("marketName", "eoemarket");
    object.put("count", 1);
    JSONArray data = new JSONArray();
    JSONObject o = new JSONObject();
    o.put("id", -1);
    o.put("link", "http://testsssssss");
    o.put("statusCode", 404);
    data.add(o);
    object.put("data", data);

    String test = "eyJjb3VudCI6IDEwLCAibWFya2V0TmFtZSI6ICJBcHBDaGluYSIsICJkYXRhIjogW3sibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLmdvb2dsZS5hbmRyb2lkLmFwcHMubWFwcyIsICJpZCI6IDEsICJzdGF0dXNDb2RlIjogNDA0fSwgeyJsaW5rIjogImh0dHA6Ly93d3cuYXBwY2hpbmEuY29tL2FwcC9jb20ud2VhdGhlci5XZWF0aGVyIiwgImlkIjogMiwgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5zdHlsZW0ud2FsbHBhcGVycyIsICJpZCI6IDQsICJzdGF0dXNDb2RlIjogNDA0fSwgeyJsaW5rIjogImh0dHA6Ly93d3cuYXBwY2hpbmEuY29tL2FwcC9jb20uc2hhemFtLmVuY29yZS5hbmRyb2lkIiwgImlkIjogNSwgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5yaW5nZHJvaWQiLCAiaWQiOiA2LCAic3RhdHVzQ29kZSI6IDQwNH0sIHsibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLnAxLmNob21wc21zIiwgImlkIjogNywgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5oYW5kY2VudC5uZXh0c21zIiwgImlkIjogOCwgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5mYWNlYm9vay5rYXRhbmEiLCAiaWQiOiA5LCAic3RhdHVzQ29kZSI6IDQwNH0sIHsibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLmNvZGUuaS5tdXNpYyIsICJpZCI6IDEwLCAic3RhdHVzQ29kZSI6IDQwNH0sIHsibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLmJpZ2d1LnNob3BzYXZ2eSIsICJpZCI6IDExLCAic3RhdHVzQ29kZSI6IDQwNH1dLCAia2V5IjogImpqRzhMa0MzTUh5RjlYY3NWS2g2Rkh4bXRMQ05ZdE14In0=";
    Reader input = new StringReader(object.toJSONString());
    byte[] binaryData = IOUtils.toByteArray(input, "UTF-8");
    String encodeBase64 = Base64.encodeBase64String(binaryData);
    System.out.println(encodeBase64);

    String url = "http://localhost:9080/sjk-market-admin/market/brokenLink.d";
    url = "http://app.sjk.ijinshan.com/market/brokenLink.d";
    URIBuilder builder = new URIBuilder(url);
    builder.setParameter("c", test);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(builder.build());
    HttpResponse response = httpclient.execute(httpPost);
    logger.debug("URI: {} , {}", url, response.getStatusLine());

    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    // be convinient to debug
    String rspJSON = IOUtils.toString(is, "UTF-8");
    System.out.println(rspJSON);
}
 
Example 8
Project: aliyun-cupid-sdk   File: WebProxyCall.java   View Source Code Vote up 5 votes
public void callWebProxy(String url) {
    String resultCode = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            resultCode = ResponseCode.CALLRESPONSEERROR;
            if (entity != null) {
                String responseString = EntityUtils.toString(entity);
                if (responseString.contains("Spark Jobs") && responseString.contains("Stages")
                        && responseString.contains("Storage") && responseString.contains("Environment")
                        && responseString.contains("Executors")) {
                    resultCode = ResponseCode.CALLSUCCESS;
                }
            }
        } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                || statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            resultCode = ResponseCode.CALLFORBIDDEN;
        } else {
            resultCode = ResponseCode.OTHER_RESPONSE + String.valueOf(statusCode);
        }
    } catch (Exception e) {
        LOG.warn("WebProxyCall exception " + e.getMessage());
        resultCode = ResponseCode.CALLEXCEPTION;
    } finally {
        httpclient.close();
    }
    LOG.info("WebProxyCall result " + resultCode);
    if (!resultCode.equals(ResponseCode.CALLSUCCESS)) {
        System.exit(1);
    }
}
 
Example 9
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View Source Code Vote up 5 votes
public static void deleteForest(String fName){
	try{
		DefaultHttpClient client = new DefaultHttpClient();
		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));

		HttpDelete delete = new HttpDelete("http://"+host+":8002/manage/v2/forests/"+fName+"?level=full");
		client.execute(delete);

	}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}
}
 
Example 10
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View Source Code Vote up 5 votes
public static void createRESTServerWithDB(String restServerName,int restPort)	{
	try{
		DefaultHttpClient client = new DefaultHttpClient();

		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));
		HttpPost post = new HttpPost("http://"+host+":8002"+ "/v1/rest-apis?format=json");
		//			
		String JSONString = 
				"{ \"rest-api\": {\"name\":\""+
						restServerName +
						"\",\"port\":\""+
						restPort+
						"\"}}";
		//System.out.println(JSONString);		
		post.addHeader("Content-type", "application/json");
		post.setEntity(new StringEntity(JSONString));

		HttpResponse response = client.execute(post);
		HttpEntity respEntity = response.getEntity();

		if (respEntity != null) {
			// EntityUtils to get the response content
			String content =  EntityUtils.toString(respEntity);
			System.out.println(content);
		}
	}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}
}
 
Example 11
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View Source Code Vote up 5 votes
public static void detachForest(String dbName, String fName){
	try{
		DefaultHttpClient client = new DefaultHttpClient();

		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));

		HttpPost post = new HttpPost("http://"+host+":8002"+ "/manage/v2/forests/"+fName);
		//			
		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("state", "detach"));
		urlParameters.add(new BasicNameValuePair("database", dbName));

		post.setEntity(new UrlEncodedFormEntity(urlParameters));

		HttpResponse response = client.execute(post);
		HttpEntity respEntity = response.getEntity();

		if (respEntity != null) {
			// EntityUtils to get the response content
			String content =  EntityUtils.toString(respEntity);
			System.out.println(content);
		}
	}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}	
}
 
Example 12
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View Source Code Vote up 5 votes
public static void deleteElementRangeIndexTemporalCollection(String dbName, String collectionName) throws Exception
{
	DefaultHttpClient client = new DefaultHttpClient();
	client.getCredentialsProvider().setCredentials(
			new AuthScope(host, 8002),
			new UsernamePasswordCredentials("admin", "admin"));

	HttpDelete del = new HttpDelete("http://"+host+":8002/manage/v2/databases/"+ dbName + "/temporal/collections?collection=" + collectionName + "&format=json");

	del.addHeader("Content-type", "application/json");
	del.addHeader("accept", "application/json");

	HttpResponse response = client.execute(del);
	HttpEntity respEntity = response.getEntity();
	if( response.getStatusLine().getStatusCode() == 400)
	{
		HttpEntity entity = response.getEntity();
		String responseString = EntityUtils.toString(entity, "UTF-8");
		System.out.println(responseString);
	}
	else if (respEntity != null) {
		// EntityUtils to get the response content
		String content =  EntityUtils.toString(respEntity);
		System.out.println(content);
	}
	else {
		System.out.println("Collection: " + collectionName + " deleted");
		System.out.println("==============================================================");
	}
}
 
Example 13
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View Source Code Vote up 5 votes
public static void deleteElementRangeIndexTemporalAxis(String dbName, String axisName) throws Exception
{
	DefaultHttpClient client = new DefaultHttpClient();
	client.getCredentialsProvider().setCredentials(
			new AuthScope(host, 8002),
			new UsernamePasswordCredentials("admin", "admin"));

	HttpDelete del = new HttpDelete("http://"+host+":8002/manage/v2/databases/"+ dbName + "/temporal/axes/" + axisName + "?format=json");

	del.addHeader("Content-type", "application/json");
	del.addHeader("accept", "application/json");

	HttpResponse response = client.execute(del);
	HttpEntity respEntity = response.getEntity();
	if( response.getStatusLine().getStatusCode() == 400)
	{
		HttpEntity entity = response.getEntity();
		String responseString = EntityUtils.toString(entity, "UTF-8");
		System.out.println(responseString);
	}
	else if (respEntity != null) {
		// EntityUtils to get the response content
		String content =  EntityUtils.toString(respEntity);
		System.out.println(content);
	}
	else {
		System.out.println("Axis: " + axisName + " deleted");
		System.out.println("==============================================================");
	}
}
 
Example 14
Project: rainbow   File: HttpUtil.java   View Source Code Vote up 5 votes
public static Object HttpPost(String aUrl, String aPostData) {
    String res = "";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpost = new HttpPost(aUrl);
    try {
        httpost.setEntity(new StringEntity(aPostData, "UTF-8"));
        HttpResponse response = httpClient.execute(httpost);
        res = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return res;
}
 
Example 15
Project: sjk   File: MarketAppControllerTest.java   View Source Code Vote up 5 votes
@Test
public void testEdit() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/ijinshan/shift-to-ijinshan.json";
    URIBuilder urlb = new URIBuilder(url);
    // 318840 378460 hiapk 雨夜壁纸桌面主题
    // 318839 378435 hiapk APO极限滑板

    urlb.setParameter("ids", "318840,318839");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
 
Example 16
Project: Trinity-App   File: GetDataJSON.java   View Source Code Vote up 5 votes
@Override
protected String doInBackground(String... params) {
    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("http://djtrinity.in/app/api/events.php");

    // Depends on your web service
    httppost.setHeader("Content-type", "application/json");

    InputStream inputStream = null;
    String result = null;
    try {
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        result = sb.toString();
    } catch (Exception e) {
        // Oops
    } finally {
        try {
            if (inputStream != null) inputStream.close();
        } catch (Exception squish) {
        }
    }
    return result;
}
 
Example 17
Project: sjk   File: ControllerTest.java   View Source Code Vote up 5 votes
@Test
public void testbrokenLink() throws IOException, URISyntaxException {

    JSONObject object = new JSONObject();
    object.put("key", "sprSCKKWf8xUeXxEo6Bv0lE1sSjWRDkO");
    object.put("marketName", "eoemarket");
    object.put("count", 1);
    JSONArray data = new JSONArray();
    JSONObject o = new JSONObject();
    o.put("id", -1);
    o.put("link", "http://testsssssss");
    o.put("statusCode", 404);
    data.add(o);
    object.put("data", data);

    Reader input = new StringReader(object.toJSONString());
    byte[] binaryData = IOUtils.toByteArray(input, "UTF-8");
    String encodeBase64 = Base64.encodeBase64String(binaryData);

    String url = "http://localhost:8080/sjk-market/market/brokenLink.d";
    url = "http://app-t.sjk.ijinshan.com/market/brokenLink.d";
    URIBuilder builder = new URIBuilder(url);
    builder.setParameter("c", encodeBase64);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(builder.build());
    HttpResponse response = httpclient.execute(httpPost);
    logger.debug("URI: {} , {}", url, response.getStatusLine());

    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    // be convinient to debug
    String rspJSON = IOUtils.toString(is, "UTF-8");
    System.out.println(rspJSON);
}
 
Example 18
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View Source Code Vote up 5 votes
public static void createForestonHost(String fName,String dbName,String hName)	{
	try{
		DefaultHttpClient client = new DefaultHttpClient();
		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));
		HttpPost post = new HttpPost("http://"+host+":8002"+ "/manage/v2/forests?format=json");
		String JSONString = 
				"{\"database\":\""+ 
						dbName + 
						"\",\"forest-name\":\""+
						fName+
						"\",\"host\":\""+hName+"\"}" 
						;
		//			System.out.println(JSONString);
		post.addHeader("Content-type", "application/json");
		post.setEntity(new StringEntity(JSONString));

		HttpResponse response = client.execute(post);
		HttpEntity respEntity = response.getEntity();

		if (respEntity != null) {
			// EntityUtils to get the response content
			String content =  EntityUtils.toString(respEntity);
			System.out.println(content);
		}
	}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}
}
 
Example 19
Project: hadoop   File: WebAppProxyServlet.java   View Source Code Vote up 4 votes
/**
 * Download link and have it be the response.
 * @param req the http request
 * @param resp the http response
 * @param link the link to download
 * @param c the cookie to set if any
 * @throws IOException on any error.
 */
private static void proxyLink(HttpServletRequest req, 
    HttpServletResponse resp, URI link, Cookie c, String proxyHost)
    throws IOException {
  DefaultHttpClient client = new DefaultHttpClient();
  client
      .getParams()
      .setParameter(ClientPNames.COOKIE_POLICY,
          CookiePolicy.BROWSER_COMPATIBILITY)
      .setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
  // Make sure we send the request from the proxy address in the config
  // since that is what the AM filter checks against. IP aliasing or
  // similar could cause issues otherwise.
  InetAddress localAddress = InetAddress.getByName(proxyHost);
  if (LOG.isDebugEnabled()) {
    LOG.debug("local InetAddress for proxy host: {}", localAddress);
  }
  client.getParams()
      .setParameter(ConnRoutePNames.LOCAL_ADDRESS, localAddress);
  HttpGet httpGet = new HttpGet(link);
  @SuppressWarnings("unchecked")
  Enumeration<String> names = req.getHeaderNames();
  while(names.hasMoreElements()) {
    String name = names.nextElement();
    if(passThroughHeaders.contains(name)) {
      String value = req.getHeader(name);
      if (LOG.isDebugEnabled()) {
        LOG.debug("REQ HEADER: {} : {}", name, value);
      }
      httpGet.setHeader(name, value);
    }
  }

  String user = req.getRemoteUser();
  if (user != null && !user.isEmpty()) {
    httpGet.setHeader("Cookie",
        PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
  }
  OutputStream out = resp.getOutputStream();
  try {
    HttpResponse httpResp = client.execute(httpGet);
    resp.setStatus(httpResp.getStatusLine().getStatusCode());
    for (Header header : httpResp.getAllHeaders()) {
      resp.setHeader(header.getName(), header.getValue());
    }
    if (c != null) {
      resp.addCookie(c);
    }
    InputStream in = httpResp.getEntity().getContent();
    if (in != null) {
      IOUtils.copyBytes(in, out, 4096, true);
    }
  } finally {
    httpGet.releaseConnection();
  }
}
 
Example 20
Project: PaoMovie   File: HttpUtil.java   View Source Code Vote up 4 votes
public static String postAPI(Map<String, String> params, String remoteServiceUrl, String loginName, String pwd) {
	String result = "";

	// 请求参数
	List<NameValuePair> list = new ArrayList<NameValuePair>();
	List<String> listStr = new ArrayList<String>();

	for (String key : params.keySet()) {
		listStr.add("\"" + key + "\":\"" + params.get(key) + "\"");
	}

	list.add(new BasicNameValuePair("", "{" + StringUtil.join(",", listStr) + "}"));

	InputStream inputStream = null;
	try {
		HttpEntity entity = new UrlEncodedFormEntity(list, "utf-8");
		HttpPost post = new HttpPost(remoteServiceUrl);
		post.setHeader("Cookie", "UserId=" + loginName + ";UserPwd=" + pwd + "");

		post.setEntity(entity);

		DefaultHttpClient client = new DefaultHttpClient();

		// 发送Http请求并获取响应
		HttpResponse response = client.execute(post);

		if (response.getStatusLine().getStatusCode() == 200) {
			// 获取响应的消息实体
			entity = response.getEntity();

			// 获取输入流
			inputStream = entity.getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

			String line = "";

			while ((line = reader.readLine()) != null) {
				result += line;
			}
		}
	} catch (Exception exp) {
		result = null;
		exp.printStackTrace();
	} finally {
		try {
			if (inputStream != null)
				inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	return result;
}