有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java身份验证问题。。!!在ANDROID上使用HTTPURLCONNECTION

“基本YWRtaW46YW RtaW4=” 是我地址的正确代码。我检查j2me项目

在安卓上,我的getbase64方法返回“Basic YWRtaW46YW” RtaW4=“这是真的

和ı将其用于:

httpConnection。setRequestProperty(“授权”,getBase64Encode())

最后,响应代码是401

有什么想法吗

protected void connect() {
  InputStream is = null;
  OutputStream os = null;
  try {

   url = new URL(getUrl());
   System.out.println(getUrl());// duzelt
   queryString = encodeURL(queryString);
   byte postmsg[] = queryString.getBytes("UTF-8");
   conn = url.openConnection();
   if (!(conn instanceof HttpURLConnection))
    throw new IOException("Not an HTTP connection");

   httpConnection = (HttpURLConnection) conn;
   HttpOptions options=new HttpOptions();
   httpConnection.setDoInput(true);
   httpConnection.setDoOutput(true);
   httpConnection.setRequestMethod("GET");
   httpConnection.setRequestProperty("Authorization",
     getBase64Encode());
   httpConnection.connect();
   os = httpConnection.getOutputStream();// ///////////////////baglantının
   System.out.println("response code: "+ httpConnection.getResponseCode());
   // connect olup olmadıgını
   // kontrol et

   for (int i = 0; i < postmsg.length; i++) {
    os.write(postmsg[i]);
   }
   if (!cancel) {
    onReturn(httpConnection.getResponseCode(), httpConnection
      .getInputStream());
   }
   os.close();
   // httpConnection.close();
  } catch (Exception e) {
   System.out.println(e.getMessage());
   try {
    httpConnection.disconnect();
    Thread.sleep(60);
    // cancel=true; eklenmesı gerekebilir
   } catch (Exception ie) {
   }
   onError(e);
  }

共 (1) 个答案

  1. # 1 楼答案

    HttpURLConnection上有一个setConnectTimeout(int)方法

    Sets the timeout value in milliseconds for establishing the connection to the resource pointed by this URLConnection instance. A SocketTimeoutException is thrown if the connection could not be established in this time. Default is 0 which stands for an infinite timeout.

    httpConnection.setConnectTimeout(10000); /* connection timeout set to 10s */