java - multiple http requests at same time - java

Is there a better way to send thousands of http GET requests at the same time? My code sends requests one after other. Have looked at other answers but could not figure it out. Thanks.
for (int j=0; j<4; j++) {
DefaultHttpClient httpclient = new DefaultHttpClient();
CookieStore cookieStore = httpclient.getCookieStore();
HttpGet httpget = new HttpGet("");
try {
HttpResponse response = httpclient.execute(httpget);
List<Cookie> cookies = cookieStore.getCookies();
} catch (Exception e) {}
httpclient.getConnectionManager().shutdown();
}

you should create multiple threads and each of them should perform an HTTP Request
the below link may help
http://hc.apache.org/httpclient-3.x/threading.html

Related

Java DefaultHttpClient HTTP PUT and Cookie

I'm send a request to YouTrack api to create issue.
String url = yBaseUrl + "/rest/issue?Task&"+ URLEncoder.encode(subject)+"&"+URLEncoder.encode(desc);
HttpClient client = new DefaultHttpClient();
HttpPut request = new HttpPut(url);
// add request header
((DefaultHttpClient) client).setCookieStore(cookie);
HttpResponse response = null;
//client.execute(post);
try {
response = client.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
} catch (IOException e) {
e.printStackTrace();
}
result - 403 code.
Why setCookieStore not working?
The problem was incorrect api url. Need use /rest/issue?project=Task&summary="+ URLEncoder.encode(subject)... The question is closed

Apache HTTP client, request from specific network interface

I have machine with 4 internet IP's and I want to know if I can make apache http client to make requests from specific ip/network interface
Using HttpClient 4.3 APIs
RequestConfig config = RequestConfig.custom()
.setLocalAddress(InetAddress.getByAddress(new byte[] {127,0,0,1}))
.build();
HttpGet httpGet = new HttpGet("/stuff");
httpGet.setConfig(config);
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
// do something useful
} finally {
response.close();
}
} finally {
httpClient.close();
}
Never did this, but there is a ClientConnectionOperator interface (and some factories too) in the API to create the socket. Maybe you can implement your own and create the socket with a concrete interface.

How to send HttpPost every 5 secs

In a Java, I want to send HttpPost every 5 secs without waiting for the response. How can I do that?
I use the following code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity params = new StringEntity(json.toString() + "\n");
post.addHeader("content-type", "application/json");
post.setEntity(params);
httpClient.execute(post);
Thread.sleep(5000);
httpClient.execute(post);
but it does not work.
Even though I lose the previous connection and set up a new connection to send the second, the second execute function is always blocked.
Your question leaves a bunch of questions, but the basic point of it can be achieved by:
while(true){ //process executes infinitely. Replace with your own condition
Thread.sleep(5000); // wait five seconds
httpClient.execute(post); //execute your request
}
I tried your code and I got the exception :
java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
This exception is already logged in HttpClient 4.0.1 - how to release connection?
I was able to release the connection by consuming the response with the following code:
public void sendMultipleRequests() throws ClientProtocolException, IOException, InterruptedException {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.google.com");
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
Thread.sleep(5000);
response = httpClient.execute(post);
entity = response.getEntity();
EntityUtils.consume(entity);
}
Using DefaultHttpClient is synchronous which means that program is blocked waiting for the response. Instead of that you could use async-http-client library to perform asynchronous requests (you can download jar files from search.maven.org if you're not familiar with Maven). Sample code may look like:
import com.ning.http.client.*; //imports
try {
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
while(true) {
asyncHttpClient
.preparePost("http://your.url/")
.addParameter("postVariableName", "postVariableValue")
.execute(); // just execute request and ignore response
System.out.println("Request sent");
Thread.sleep(5000);
}
} catch (Exception e) {
System.out.println("oops..." + e);
}

How to connect Android app with MySQL database through PHP

I am still a little skeptical as to how to connect my Android app to a PHP script. I saw somewhere that the following code will connect the app to the server. But I am new at android so I do not know how to really use it.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://url.to.my.app.com");
HttpResponse response = httpClient.execute(httpGet);
// handle response'
I understand that this opens a connection to an online server, but what I do not understand is what kind of response is returned by the server and how to process it. Also, I want to know how to send data through POST to the server from my app.
(If you could provide some code of your own, that would be helpful too) Thanks!
This will open a connection and send a http GET request to server. Your PHP script executes on the server side for this request and returns some contents. You can use folowing code to process the response.
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
}
For POST execution you need to do something like this.
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("test1","test1" ));
nvps.add(new BasicNameValuePair("test2", "test2" ));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}

Application getting website response

net developer and dont know about android. could you please help me to fix this code
Exception: android.os.networkmainthreadException on
client.execute(get1)
try
{
HttpGet get1 = new HttpGet ("http://www.google.com/");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get1);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
}
catch(Exception e )
{
urlview.setText( "hi bug"+ e.toString());
}
You are doing network operation on UI thread which in not allowed in android version >=3.0 So use AsyncTask

Categories