State management in httpAsyncClient - java

I am trying to set cookie in httpAsyncClient library but problem is i am not figure out to find example of it..here is my code.
public JSONArray sendRequest(List<BasicNameValuePair> postPairs){
HttpAsyncClient httpclient = null;
try {
httpclient = new DefaultHttpAsyncClient();
httpclient.start();
HttpPost post = new HttpPost("http://10.0.0.62:8080/IDocWS"+postPairs.get(0).getValue());
BasicCookieStore cookie = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE,cookie);
post.setEntity(new UrlEncodedFormEntity( postPairs, HTTP.UTF_8 ) );
Future<HttpResponse> future = httpclient.execute(post, null);
HttpResponse resp = future.get();
HttpEntity entity = resp.getEntity();
JSONArray jArray = CovnertToJson(entity);
return jArray;
and here is my ConvertToJson method
public JSONArray CovnertToJson(HttpEntity entity){
try{
InputStream inputStream1= entity.getContent();
BufferedReader reader1 = new BufferedReader(new InputStreamReader(inputStream1, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line1;
while ((line1 = reader1.readLine()) != null) {
sb.append(line1);
}
JSONArray jArray = new JSONArray(sb.toString());
return jArray;
}

First get cookie from request header:
Future<HttpResponse> future = httpclient.execute(post, null);
HttpResponse resp = future.get();
header = resp.getHeaders("cookie");
myCookies = header.toString();
After getting cookie put it in HTTPContext and send it and it shoud work.
CookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("cookie", myCookies);
cookieStore.addCookie(cookie);
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE,cookieStore);

Related

Get request with Json response?

I have the following class that return an spefic field from json response.
The method to request here is with post. How can i do it with get method?
Also i want to make the get request with headers
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(
"");
post.addHeader("Auth-Token", authenticationValues.getAuthToken());
post.addHeader("device-id", authenticationValues.getDeviceId());
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("task", "savemodel"));
String generatedJSONString = null;
params.add(new BasicNameValuePair("code", generatedJSONString));
CloseableHttpResponse response = null;
Scanner in = null;
try {
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());
while (in.hasNext()) {
JsonString += in.next();
}
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(JsonString);
JSONObject jsonObject = new JSONObject(JsonString);
JSONObject myResponse = jsonObject.getJSONObject("login");
Object myResponse2 = myResponse.get("loginStatus");
System.out.println(myResponse2);
Try this...
URL url = new URL("http://"...);
HttpURLConnection http = (HttpURLConnection)
url.openConnection();
http.setRequestMethod("GET");
http.setDoOutput(true);
http.connect();
OutputStream out = http.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(FOO);
writer.flush();
writer.close();
InputStreamReader in = new InputStreamReader(http.getInputStream());
BufferedReader br = new BufferedReader(in);
char[] chars = new char[BUF_SIZE];
int size = br.read(chars);
String response = new String(chars).substring(0, size);
All enclosed in a try-catch block.

Connection refused when using µTorrent web api programmatically through localhost

I'm trying to use the web api of µTorrent from my localhost with java. This works but sometimes I get an error in this method.
public String[] connectToWebAPI()
{
String guid = null;
String token = null;
String[] tokenAndGuid = new String[2];
targetHost = new HttpHost("127.0.0.1", 2222, "http");
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
try
{
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
localcontext = new HttpClientContext();
localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
CookieStore cookieStore = new BasicCookieStore();
localcontext.setCookieStore(cookieStore);
HttpGet httpget = new HttpGet("http://127.0.0.1:2222/gui/");
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
EntityUtils.consumeQuietly(response.getEntity());
httpget = new HttpGet("http://127.0.0.1:2222/gui/token.html");
response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity e = response.getEntity();
InputStream is = e.getContent();
StringWriter sw = new StringWriter();
IOUtils.copy(is, sw);
sw.flush();
sw.close();
is.close();
//<html><div id='token' style='display:none;'>gzB9zbMru3JJlBf2TbmwwklESgXW2hD_caJfFLvNBjmaRbLZ3kNGnSHrFlIAAAAA</div></html>
String t = sw.toString();
//Get token out of html
int start = "<html><div id='token' style='display:none;'>".length();
int end = t.indexOf("</div></html>");
token = t.substring(start,end);
EntityUtils.consumeQuietly(response.getEntity());
for(Cookie cookie : localcontext.getCookieStore().getCookies())
{
if(cookie.getName().equals("GUID"))
guid = cookie.getValue();
}
httpclient.close();
}
catch (Exception e)
{
tokenAndGuid[0] = "error";
return tokenAndGuid;
}
tokenAndGuid[0] = token;
tokenAndGuid[1] = guid;
return tokenAndGuid;
}
And the error I get is on this statement:
httpclient.execute(targetHost, httpget, localcontext);
org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:2222 [/127.0.0.1] failed: Connection refused: connect
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:140)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
Somebody who can help me with this or give me some insights?
Thank you in advance.

How to send Json String using REST to java webservice in Parameter in android?

Fiends, i sending JSON String with three parameters to java web service method. but on java side method cant print in console. Please guide me what i have to change from below code?
String json = "";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "ghanshyam");
jsonObject.put("country", "India");
jsonObject.put("twitter", "ghahhd");
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
// 6. set httpPost Entity
System.out.println(json);
httpPost.setEntity(se);
httpGet.se
// 7. Set some headers to inform server about the type of the content
//httpPost.addHeader( "SOAPAction", "application/json" );
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//String s = doGet(url).toString();
Toast.makeText(getApplicationContext(), "Data Sent", Toast.LENGTH_SHORT).show();
Use the following code to post the json to Java web-service: and get the resopnse as a string.
JSONObject json = new JSONObject();
json.put("name", "ghanshyam");
json.put("country", "India");
json.put("twitter", "ghahhd");
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpresponse = client.execute(post);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
and Your convertStremToString() method will be as follows:
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}

Enable cookies with HTTPClient

I am trying to implement a Java Code that fetch urls like this one:
http://trendistic.indextank.com/_trending-topics-archive/2011-12-25
The code I wrote is based in HTTPClient as follow:
HttpClient httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet(urls);
try {
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget, localContext);
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null) {
total.append(line+"\n");
}
System.out.println(total);
return (total.toString());
} catch (Exception e) {
e.printStackTrace();
return(e.getMessage());
}
}
Nevertheless, the response I got is:
if (tz != tzless.readCookie('local_tz')) {
// no cookies!
document.write("<h1>Cookies are not enabled for this site</h1>");
document.write("<p>In order for Trendistic to work in Internet Explorer you need to enable cookies.</p>");
document.write("<ul><li>Please enable cookies for this site and refresh this page</li><li>Or try Trendistic in a different browser such as Safari, Firefox or Chrome.</li></ul>");
} else {
self.location.reload();
}
How can I enable cookies for fetching the HTML with the dynamical results.

Apache HttpClient 4.1.1 NTLM authentication not SPNEGO

The problem here is consuming a web resource that has NTLM authentication while using the Apache HttpClient on the client side. The issue I am having is forcing the client to use NTLM authentication. here is a code sapmle.
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getAuthSchemes().register("ntlm",new NTLMSchemeFactory());
NTCredentials creds = new NTCredentials("_myUSer_","_myPass_","_myWorkstation_","_myDomain_");
httpclient.getCredentialsProvider().setCredentials( new AuthScope("serverName",80), creds);
List<String> authpref = new ArrayList<String>();
authpref.add(AuthPolicy.NTLM);
httpclient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
HttpHost target = new HttpHost("serverName", 80, "http");
HttpGet httpget = new HttpGet("webResource");
HttpContext localContext = new BasicHttpContext();
HttpResponse response = httpclient.execute(target, httpget, localContext);
Here is the error from Java:
org.apache.http.client.protocol.RequestTargetAuthentication process
SEVERE: Authentication error: Invalid name provided (Mechanism level: Could not load configuration file C:\WINDOWS\krb5.ini (The system cannot find the file specified))
The web server response is a 401.
Any ideas on why the auth policy not being set correctly?
Am I missing something in the code?
I have a similar situation and I suspect that you are setting the wrong parameter: AuthPNames.PROXY_AUTH_PREF. I use AuthPNames.TARGET_AUTH_PREF and all seems to work fine.
Here is my solution to this Problem: And "evandongen" is right.
Please note the use of the URIBuilder.
String username = "uid";
String pwd = "pwd";
String servername = "www.someserver.com";
String workstation = "myworkstation";
String domain = "somedomain";
String relativeurl = "/util/myservice.asmx";
String oldimagePath = "\\mypath\\image.jpg";
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getAuthSchemes().register("ntlm",new NTLMSchemeFactory());
NTCredentials creds = new NTCredentials(username,pwd,workstation,domain);
httpclient.getCredentialsProvider().setCredentials(new AuthScope(servername,80), creds);
List authpref = new ArrayList();
authpref.add(AuthPolicy.NTLM);
URIBuilder builder = new URIBuilder();
builder.setScheme("http")
.setHost(servername)
.setPath(relativeurl + "/DeleteImage")
.setParameter("imagePath", oldimagePath);
URI uri = builder.build();
httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
HttpHost target = new HttpHost(servicename, 80, "http");
HttpGet httpget = new HttpGet(uri);
HttpContext localContext = new BasicHttpContext();
HttpResponse response1 = httpclient.execute(target, httpget, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response1.getEntity().getContent()));
String line = reader.readLine();
while (line != null)
{
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e) {
System.out.println("Exception:"+e.toString());
} finally {
// End
}
I think this is because of a defect, see here.
HttpClient did not work for me but the below snippet did.
Reference - http://docs.oracle.com/javase/7/docs/technotes/guides/net/http-auth.html
public static String getResponse(String url, String userName, String password) throws IOException {
Authenticator.setDefault(new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
System.out.println(getRequestingScheme() + " authentication");
return new PasswordAuthentication(userName, password.toCharArray());
}
});
URL urlRequest = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
StringBuilder response = new StringBuilder();
InputStream stream = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String str = "";
while ((str = in.readLine()) != null) {
response.append(str);
}
in.close();
return response.toString();
}

Categories