에뮬레이터 상에서 파일도 찾고 byte[]의 length까지 제대로 출력되는 걸 확인했는데
자꾸 400 bad request가 돌아옵니다ㅜㅜ
파일이 제대로 첨부되지 않은건가요??
전에 이클립스 상에서 같은 코드를 썼을 때는 응답이 잘 돌아왔는데 왜 안드로이드 스튜디오에서는 400이 돌아올까요…ㅠㅠㅠ
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.file.Files;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String TAG = this.getClass().getSimpleName();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
TextView txt = findViewById(R.id.txt);
String result = "";
HttpsURLConnection conn = null;
//conn.disconnect();
try {
URL url = new URL("https://kakaoi-newtone-openapi.kakao.com/v1/recognize");
conn = (HttpsURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Transfer-Encoding", "chunked");
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("X-DSS-Service", "DICTATION");
conn.setRequestProperty("Authorization", "KakaoAK {인증키}");
conn.setDoOutput(true);
File wavfile = new File("/storage/emulated/0/Download/num.wav");
if(wavfile.exists()){
Log.d(TAG,"있다");
}else{
Log.d(TAG,"없다");
}
byte[] bytes = Files.readAllBytes(wavfile.toPath());
Log.d(TAG,"길이=="+bytes.length);
DataOutputStream request = new DataOutputStream(conn.getOutputStream());
request.write(bytes);
request.flush();
request.close();
StringBuilder sb = new StringBuilder();
Log.d(TAG,"여기2=====");
if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
Log.d(TAG,"여기3=====");
result="OK";
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
sb.append(line).append("\n");
}
in.close();
System.out.println("" + sb.toString());
result = sb.toString();
Log.d(TAG,"여기=====");
conn.disconnect();
} else {
Log.d(TAG,"여기4=====");
System.out.println(conn.getResponseMessage());
result = conn.getResponseCode()+conn.getResponseMessage();
}
} catch (Exception e){
Log.d(TAG,"여기5=====");
System.err.println(e.toString());
}
txt.setText(result);
}
}