How to cancel a thread making an http request from another thread

Any suggestion on how we can kill the thread that made the http post request and waited for a response. I want to kill this thread from another thread running in parallel before it can receive a response from the request. I had a suggestion to close or abort the http post request, but does not work, can anyone suggest how we can abort the HTTP request in this scenario, or any other way to achieve this.

+3


source to share


2 answers


The thread that made the request is blocked waiting for a server response. If you take a thread dump and see it, it will be in some read () method, but not on Thread.sleep. Therefore, calling interrupt () will have no effect (unless it is interrupted). Do you have access to the socket or output stream on which the POST request was made? If so, you can close this, which will drop out of the expected read with an exception. Do you have some sample code you can supply?



+1


source


Hello everything is finally implemented and this socket closing idea works. below is the snippet I tried.

my requesting thread

package com.pkg.myhttptest;

import org.apache.http.client.methods.HttpPost;

public class RequestThread implements Runnable{

    Message msg = null;
    Util util = null;
    public RequestThread(Message msg, Util util) {
        this.msg = msg;
        this.util = util;
    }
    public void run() {
        System.out.println("its request thread");
        util.print(msg);
    }



}

      

Cancel topic

public class CancelThread implements Runnable {
    Message msg = null;
    Util util = null;
    public CancelThread(Message msg, Util util) {
        this.msg = msg;
        this.util = util;
    }
    public void run() {
        System.out.println("its cancel thread");
        int i=0;
        while(i<5){
            System.out.println("looping" + i);
            i++;
        }
        System.out.println(msg.getHttpost() + "In cancelled");
        Header[] hdr = msg.getHttpost().getAllHeaders();
        System.out.println(hdr.length + "length");
        msg.getHttpost().abort();
        System.out.println(msg.getHttpost().isAborted());

    }

}

      

Shared object

public class Message {

    HttpPost httpost;

    public HttpPost getHttpost() {
        return httpost;
    }

    public void setHttpost(HttpPost httpost) {
        this.httpost = httpost;
    }
}

      



Utility class

public class Util {
    private final String USER_AGENT = "Mozilla/5.0";

    public void print(Message msg) {
        String url = "https://selfsolve.apple.com/wcResults.do";
        HttpPost post = new HttpPost(url);
        HttpClient client = HttpClientBuilder.create().build(); 
        post.setHeader("User-Agent", USER_AGENT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
        urlParameters.add(new BasicNameValuePair("cn", ""));
        urlParameters.add(new BasicNameValuePair("locale", ""));
        urlParameters.add(new BasicNameValuePair("caller", ""));
        urlParameters.add(new BasicNameValuePair("num", "12345"));

        try {
            post.setEntity(new UrlEncodedFormEntity(urlParameters));
            msg.setHttpost(post);
            HttpResponse response = client.execute(post);
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
        } catch (UnsupportedEncodingException e) {

        } catch (IOException e) {
           e.printStackTrace()
        }
    }

      

Main class

public class App 
{
    public static void main( String[] args )
    {
        Message msg = new Message();
        Util util = new Util();

        Thread reqThread = new Thread(new RequestThread(msg, util));
        Thread cancelThread = new Thread(new CancelThread(msg, util));

        System.out.println("Starting Threads");
        reqThread.start();
        try {
            reqThread.sleep(2000);
            cancelThread.start();
            cancelThread.join();
            System.out.println("closing..");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

      

Its a little raw code I agree, but it works. This results in the following exception and kills the thread.

java.net.SocketException: Socket is closed
    at java.net.Socket.getInputStream(Socket.java:876)
    at sun.security.ssl.SSLSocketImpl.doneConnect(SSLSocketImpl.java:644)
    at sun.security.ssl.SSLSocketImpl.<init>(SSLSocketImpl.java:549)

      

Thanks to everyone who did their best to help me.

+1


source







All Articles